Class Microservice
- All Implemented Interfaces:
ConfigEventListener
A microservice defines a simple API for starting and stopping simple Java services contained in executable jars.
The general command for creating and starting a microservice from a main method is as follows:
Your microservice class must be specified as the
Microservice Configuration
This class defines the following method for accessing configuration for your microservice:-
getArgs()
- The command-line arguments passed to the jar file. -
getConfig()
- An external INI-style configuration file. -
getManifest()
- The manifest file for the main jar file.
Lifecycle Methods
Subclasses must implement the following lifecycle methods:-
init()
- Gets executed immediately following construction. -
start()
- Gets executed during startup. -
stop()
- Gets executed when 'exit' is typed in the console or an external shutdown signal is received. -
kill()
- Can be used to forcibly shut down the service. Doesn't get called during normal operation.
See Also:
-
Nested Class Summary
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic Microservice.Builder
create()
Creates a new builder for this object.void
Prints a localized message to STDERR.executeCommand
(String command, String input, Object... args) Convenience method for executing a console command directly.boolean
executeCommand
(Args args, Scanner in, PrintWriter out) Executes a console command.void
exit()
Stops the console (if it's started) and callsSystem.exit(int)
.getArgs()
Returns the command-line arguments passed into the application.Returns the external INI-style configuration file that can be used to configure your microservice.final Map<String,
ConsoleCommand> Returns the console commands associated with this microservice.protected Scanner
Returns the console reader.protected PrintWriter
Returns the console writer.static Microservice
Returns the Microservice instance.Returns the logger for this microservice.Returns the main jar manifest file contents as a simpleJsonMap
.Returns the variable resolver for resolving variables in strings and files.init()
Initializes this microservice.join()
Joins the application with the current thread.void
kill()
Kill the JVM by callingSystem.exit(2); .protected void
Logs a message to the log file.void
onConfigChange
(ConfigEvents events) Gets called immediately after a config file has been loaded.void
Prints a localized message to the console writer.protected File
resolveFile
(String path) Resolves the specified path.start()
Start this application.Starts the console thread for this microservice.stop()
Stop this application.Stops the console thread for this microservice.
-
Constructor Details
-
Microservice
Constructor.- Parameters:
builder
- The builder containing the settings for this microservice.- Throws:
IOException
- Problem occurred reading file.ParseException
- Malformed input encountered.
-
-
Method Details
-
getInstance
Returns the Microservice instance.This method only works if there's only one Microservice instance in a JVM. Otherwise, it's just overwritten by the last instantiated microservice.
- Returns:
- The Microservice instance, or
null if there isn't one.
-
create
Creates a new builder for this object.- Returns:
- A new microservice builder.
-
resolveFile
Resolves the specified path.If the working directory has been explicitly specified, relative paths are resolved relative to that.
- Parameters:
path
- The path to resolve.- Returns:
- The resolved path.
-
init
Initializes this microservice.This method can be called whenever the microservice is not started.
It will initialize (or reinitialize) the console commands, system properties, and logger.
- Returns:
- This object.
- Throws:
ParseException
- Malformed input encountered.IOException
- Couldn't read a file.
-
start
Start this application.Overridden methods MUST call this method FIRST so that the
MicroserviceListener.onStart(Microservice)
method is called.- Returns:
- This object.
- Throws:
Exception
- Error occurred.
-
startConsole
Starts the console thread for this microservice.- Returns:
- This object.
- Throws:
Exception
- Error occurred
-
stopConsole
Stops the console thread for this microservice.- Returns:
- This object.
- Throws:
Exception
- Error occurred
-
getArgs
Returns the command-line arguments passed into the application.This method can be called from the class constructor.
See
Args
for details on using this method.- Returns:
- The command-line arguments passed into the application.
-
getConfig
Returns the external INI-style configuration file that can be used to configure your microservice.The config location is determined in the following order:
- The first argument passed to the microservice jar.
-
The
Main-Config entry in the microservice jar manifest file. -
The name of the microservice jar with a
".cfg" suffix (e.g."mymicroservice.jar" ->"mymicroservice.cfg" ).
If all methods for locating the config fail, then this method returns an empty config.
Subclasses can set their own config file by using the following methods:
String variables are automatically resolved using the variable resolver returned by
getVarResolver()
.This method can be called from the class constructor.
Example:
#-------------------------- # My section #-------------------------- [MySection] # An integer anInt = 1# A boolean aBoolean = true# An int array anIntArray = 1,2,3# A POJO that can be converted from a String aURL = http://foo# A POJO that can be converted from JSON aBean = {foo:'bar',baz:123}# A system property locale = $S{java.locale, en_US}# An environment variable path = $E{PATH, unknown}# A manifest file entry mainClass = $MF{Main-Class}# Another value in this config file sameAsAnInt = $C{MySection/anInt}# A command-line argument in the form "myarg=foo" myArg = $A{myarg}# The first command-line argument firstArg = $A{0}# Look for system property, or env var if that doesn't exist, or command-line arg if that doesn't exist. nested = $S{mySystemProperty,$E{MY_ENV_VAR,$A{0}}}# A POJO with embedded variables aBean2 = {foo:'$A{0}',baz:$C{MySection/anInt}}// Java code for accessing config entries above. Configconfig = getConfig();int anInt =config .get("MySection/anInt" ).asInteger().orElse(-1);boolean aBoolean =config .get("MySection/aBoolean" ).asBoolean().orElse(false );int []anIntArray =config .get("MySection/anIntArray" ).as(int [].class ).orElse(null ); URLaURL =config .get("MySection/aURL" ).as(URL.class ).orElse(null ); MyBeanaBean =config .get("MySection/aBean" ).as(MyBean.class ).orElse(null ); Localelocale =config .get("MySection/locale" ).as(Locale.class ).orElse(null ); Stringpath =config .get("MySection/path" ).orElse(null ); StringmainClass =config .get("MySection/mainClass" ).orElse(null );int sameAsAnInt =config .get("MySection/sameAsAnInt" ).asInteger().orElse(null ); StringmyArg =config .getString("MySection/myArg" ); StringfirstArg =config .getString("MySection/firstArg" );- Returns:
- The config file for this application, or
null if no config file is configured.
-
getManifest
Returns the main jar manifest file contents as a simpleJsonMap
.This map consists of the contents of
Manifest.getMainAttributes()
with the keys and entries converted to simple strings.This method can be called from the class constructor.
Example:
// Get Main-Class from manifest file. StringmainClass = Microservice.getManifest ().getString("Main-Class" ,"unknown" );// Get Rest-Resources from manifest file. String[]restResources = Microservice.getManifest ().getStringArray("Rest-Resources" );- Returns:
- The manifest file from the main jar, or
null if the manifest file could not be retrieved.
-
getVarResolver
Returns the variable resolver for resolving variables in strings and files.Variables can be controlled by the following methods:
- Returns:
- The VarResolver used by this Microservice, or
null if it was never created.
-
getLogger
Returns the logger for this microservice.- Returns:
- The logger for this microservice.
-
executeCommand
Executes a console command.- Parameters:
args
- The command arguments.
The first entry in the arguments is always the command name.in
- Console input.out
- Console output.- Returns:
true if the command returnedtrue meaning the console thread should exit.
-
executeCommand
Convenience method for executing a console command directly.Allows you to execute a console command outside the console by simulating input and output.
- Parameters:
command
- The command name to execute.input
- Optional input to the command. Can benull .args
- Optional command arguments to pass to the command.- Returns:
- The command output.
-
join
Joins the application with the current thread.Default implementation is a no-op.
- Returns:
- This object.
- Throws:
Exception
- Error occurred
-
stop
Stop this application.Overridden methods MUST call this method LAST so that the
MicroserviceListener.onStop(Microservice)
method is called.- Returns:
- This object.
- Throws:
Exception
- Error occurred
-
exit
Stops the console (if it's started) and callsSystem.exit(int)
.- Throws:
Exception
- Error occurred
-
kill
Kill the JVM by callingSystem.exit(2); . -
getConsoleCommands
Returns the console commands associated with this microservice.- Returns:
- The console commands associated with this microservice as an unmodifiable map.
-
getConsoleReader
Returns the console reader.Subclasses can override this method to provide their own console input.
- Returns:
- The console reader. Never
null .
-
getConsoleWriter
Returns the console writer.Subclasses can override this method to provide their own console output.
- Returns:
- The console writer. Never
null .
-
out
Prints a localized message to the console writer.Ignored if
"Console/enabled" isfalse .- Parameters:
mb
- The message bundle containing the message.messageKey
- The message key.args
- OptionalMessageFormat
-style arguments.
-
err
Prints a localized message to STDERR.Ignored if
"Console/enabled" isfalse .- Parameters:
mb
- The message bundle containing the message.messageKey
- The message key.args
- OptionalMessageFormat
-style arguments.
-
log
Logs a message to the log file.- Parameters:
level
- The log level.message
- The message text.args
- OptionalMessageFormat
-style arguments.
-
onConfigChange
Description copied from interface:ConfigEventListener
Gets called immediately after a config file has been loaded.- Specified by:
onConfigChange
in interfaceConfigEventListener
- Parameters:
events
- The change events.
-