Sean Liang
Sean Liang

Reputation: 213

Run multiple spring boot jars in one jvm

My project contains several services, each one is annotated with @SpringBootApplication and can be run on a random port via "gradle bootRun".

Is it possible to build the services into jars and run them together in one JVM? Not matter by programmatic method or just put them in a container.

Please show me some instructions if possible. Thanks!

Upvotes: 16

Views: 19239

Answers (4)

Yuefeng Li
Yuefeng Li

Reputation: 463

This is applicable, as David Tanzer said, by using two classloaders to start each Spring application in one JVM process. And no special code changes are required for these Spring apps.

In this way, almost every resource under those classloaders are separated: spring beans, class instances and even static fields of a same class.

But there are still concerns if you decide to hack like this:

  • Some resources like ports, cannot be reused in one JVM;
  • JVM system properties are shared within JVM process so pay attention if those two apps are reading a system property with same name. If you are using Spring, could try setting properties via command line argument to override those from system properties.
  • Classes loaded by the system class loader or its parents will share static fields and class definitions. For example, Spring Boot's thin jar launcher will use the system class loader to load bean class definition by default so there will be only one class definition even you have launched Spring apps in separate class loaders.

Upvotes: 1

Rameez Shikalgar
Rameez Shikalgar

Reputation: 21

If you want to launch multiple spring boot microservices in single JVM then you can achieve this by launching multiple threads. Please refer sample code here https://github.com/rameez4ever/springboot-demo.git

Upvotes: 1

David Tanzer
David Tanzer

Reputation: 2742

It's a little hacky, but can be done. I wrote a blog post about it some time ago: Running Multiple Spring Boot Apps in the Same JVM. The basic idea is to run every Spring Boot application in a different classloader (because otherwise there would be resource conflicts).

I, personally, only used it for testing. I would prefer to run the different applications in different docker containers in production. But for testing it's pretty cool: You can quickly boot up your application and debug everything...

Upvotes: 13

iamiddy
iamiddy

Reputation: 3073

Yes you can please check this SO.

However, if separating the running-user processes and simplicity is core , I would recommend the use of Docker containers, each running instance of the container(your apps) will runs in its own JVM on the same or distributed host

Upvotes: 0

Related Questions