Grails Goodness: Save Application PID in File
Since Grails 3 we can borrow a lot of the Spring Boot features in our applications. If we look in our Application.groovy
file that is created when we create a new Grails application we see the class GrailsApp
. This class extends SpringApplication
so we can use all the methods and properties of SpringApplication
in our Grails application. Spring Boot and Grails comes with the class ApplicationPidFileWriter
in the package org.springframework.boot.actuate.system
. This class saves the application PID (Process ID) in a file application.pid
when the application starts.
In the following example Application.groovy
we create an instance of ApplicationPidFileWriter
and register it with the GrailsApp
:
package mrhaki.grails.sample
import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import org.springframework.boot.actuate.system.ApplicationPidFileWriter
class Application extends GrailsAutoConfiguration {
static void main(String\[\] args) {
final GrailsApp app = new GrailsApp(Application)
// Register PID file writer.
app.addListeners(new ApplicationPidFileWriter())
app.run(args)
}
}
So when we run our application a new file application.pid
is created in the current directory and contains the PID:
$ grails run-app
From another console we read the contents of the file with the PID:
$ cat application.pid
20634
$
The default file name is application.pid
, but we can use another name if we want to. We can use another constructor for the ApplicationPidFileWriter
where we specify the file name. Or we can use a system property or environment variable with the name PIDFILE
. But we can also set it with the configuration property spring.pidfile
. We use the latest option in our Grails application. In the next example application.yml
we set this property:
...
spring:
pidfile: sample-app.pid
...
When we start our Grails application we get the file sample-app.pid
with the application PID as contents.
Written with Grails 3.0.1.