Writing Microservices With msf4j (Microservices Framework for Java)
Learn how to write and test microservices with Java in the Microservices Framework for Java, also known as msf4j, in this tutorial.
Join the DZone community and get the full member experience.
Join For FreeMicroservices are taking over the enterprise and changing the way people write software within an enterprise ecosystem.
Let's build microservices with msf4j (Microservices Framework for Java) for Auto Mobile.
1) Create msf4j using Apache Archetype with the below command:
mvn archetype:generate -DarchetypeGroupId=org.wso2.msf4j -DarchetypeArtifactId=msf4j-microservice -DarchetypeVersion=1.0.0 -DgroupId=org.example -DartifactId=automobile -Dversion=0.1-SNAPSHOT -Dpackage=org.example.service -DserviceClass=AutomobileService
2) Open it in your IDEs, IDEA and Eclipse, respectively, by going into the directory:
mvn idea:idea
mvn eclipse:eclipse
3) Change the context from "/service" to "/automobile."
4) Create a new Java class called “Automobile” that will contain the blueprint for our microservices. You can use the auto-generator build getter, setter, and constructor.
public class Automobile {
private String brand;
private String name;
private int engineeSize;
private double price;
}
5) Improve the GET and POST as below:
@Path("/automobile")
public class AutomobileService {
private Map<String, Automobile> automobiles = new HashMap<>();
public AutomobileService() {
automobiles.put("toyota", new Automobile("Toyota", "Prado", 2800, 21.3));
}
@GET
@Path("/{brand}")
@Produces("application/json")
public Response get(@PathParam("brand") String brand) {
Automobile automobile = automobiles.get(brand);
return automobile == null ?
Response.status(Response.Status.NOT_FOUND).entity("{\"result\":\"brand not found = " + brand + "\"}")
.build() :
Response.status(Response.Status.OK).entity(automobile).build();
}
@POST
@Consumes("application/json")
public Response addStock(Automobile automobile) {
if(automobiles.get(automobile.getBrand()) != null) {
return Response.status(Response.Status.CONFLICT).build();
}
automobiles.put(automobile.getBrand(), automobile);
return Response.status(Response.Status.OK).
entity("{\"result\":\"Updated the automobile with brand = " + automobile.getBrand() + "\"}").build();
}
6) Build it with Maven:
maven clean install
7) Run it and test it.
java -jar target/automobile-0.1-SNAPSHOT.jar
8) Go to Postman and test GET and POST:
POST request:
Then check that the post has the recorded value:
Now, you can try DELETE and PUT by yourself.
Published at DZone with permission of Madhuka Udantha, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments