One of my Microservice [MS1
] checks another Microservice [MS2
] at startup, if MS2 is running or not. If MS2 is running MS1 will start else fails to start.
But currently I am running MS2
on my local machine which takes a huge amount of RAM
ans slow down my machine.
Is there any mechanism so that when MS1 starts and look-up for MS2 it seems that MS2 is running without actually running real MS2?
Update :
Let's assume MS2 is running on localhost:1234
and now MS1 will connect to it using REST.
You can have a look at WireMock
which is a simulator of HTTP API so it will be suitable for local development. When using it you will be able to mimic a microservice as if it was running as a standalone microservice on given host and port.
You can run it both as a standalone process and as a part of your spring application.
Option 1 - configuring standalone wiremock server :
- Download Wiremock Standalone jar
- Run standalone server on localhost with port
1234
:
java -jar wiremock-standalone-2.24.0.jar --port 1234
- Configure your MS1 microservice to use
localhost:1234
as your MS2 host. - Mock your MS2(mocked with wiremock) endpoint with some response :
curl -X POST --data '{ "request": { "url": "/yourendpoint", "method": "GET" }, "response": { "status": 200, "body": "Response" }}' http://localhost:1234/__admin/mappings/new
Here we make a mock that when you hit on your mocked server on /yourendpoint
with HTTP GET you will receive text Response
as response.
- Now when you hit with GET on
localhost:1234/yourendpoint
you get your mocked response :
curl http://localhost:1234/yourendpoint
Response
Full example can be found at Wiremock Standalone docs
Option 2 - configuring WireMock server in your Spring app :
- Add
WireMock dependency
to your project (watch out to add it not only to test scope) - Create a Spring bean used to set up your server :
@Component
public class CustomMicroserviceMock {
private WireMockServer wireMockServer;
public CustomMicroserviceMock() {
wireMockServer = new WireMockServer(options().port(1234));
wireMockServer.stubFor(get(urlEqualTo("/yourendpoint"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/plain")
.withBody("Response")));
wireMockServer.start();
}
@PreDestroy
void preDestroy() {
wireMockServer.stop();
}
}
- When we hit
localhost:1234/yourendpoint
we get response :Response
This is just a POC how it could look like but it works in both cases.