Loading...

February 5, 2016

Grails Goodness: Saving Server Port In A File

In a previous post we learned how to save the application PID in a file when we start our Grails application. We can also save the port number the application uses in a file when we run our Grails application. We must use the class EmbeddedServerPortFileWriter and add it as a listener to the GrailsApp instance. By default the server port is saved in a file application.port. But we can pass a custom file name or File object to the constructor of the EmbeddedServerPortFileWriter class.

In the following example we use the file name application.server.port to store the port number:

// File: grails-app/init/sample/Application.groovy
package sample

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import groovy.transform.CompileStatic
import org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter

@CompileStatic
class Application extends GrailsAutoConfiguration {

    static void main(String[] args) {
        final GrailsApp app = new GrailsApp(Application)

        // Save port number in file name application.server.port
        final EmbeddedServerPortFileWriter serverPortFileWriter =
                new EmbeddedServerPortFileWriter('application.server.port')

        // Add serverPortFileWriter as application listener
        // so the port number is saved when we start
        // our Grails application.
        app.addListeners(serverPortFileWriter)
        
        app.run(args)
    }
    
}

When the application is started we can find the file application.server.port in the directory from where the application is started. When we open it we see the port number:

$ cat application.server.port
8080
$

Written with Grails 3.1.