Heroku Gradle Plugin
To deploy our server application directly to Heroku, we will use the heroku-gradle plugin. Add the following to plugins
declaration of your build.gradle
:
id "com.heroku.sdk.heroku-gradle" version "2.0.0"
So your plugins
declaration must look like this:
plugins {
id 'java'
id "com.heroku.sdk.heroku-gradle" version "2.0.0"
}
Moreover, you need to add a configuration for the heroku-gradle
plugin; add the following to your build.gradle
:1
heroku {
jdkVersion = 11
processTypes(web: "java -jar build/libs/course-search-api-0.0.1.jar")
}
Notice the jdkVersion
must be the same as your Java SDK version. Moreover, the command in processTypes
is the same command we used to run the API server from the terminal after we had packaged it into a single JAR file.
Port on Heroku
Before we deploy, we need to make an adjustment to our server application; when we run our server locally, by default, Spark runs on port 4567
. Heroku assigns your application a new port every time you deploy it, so we have to find this port and tell Spark to use it.
Add the following method to ApiServer
class:
private static int getHerokuAssignedPort() {
// Heroku stores port number as an environment variable
String herokuPort = System.getenv("PORT");
if (herokuPort != null) {
return Integer.parseInt(herokuPort);
}
//return default port if heroku-port isn't set (i.e. on localhost)
return 4567;
}
Update the main
method in ApiServer
class:
public class ApiServer {
public static void main(String[] args) {
+ port(getHerokuAssignedPort());
// the rest has not changed
Run the API server (from within IntelliJ). Then, go to Postman and send a Get request to http://localhost:4567/api/courses to get the list of sample courses.
You can place the heroku
configuration anywhere in the build.gradle
file; mine is at the end of the file.