MSF4J is a framework that provides WSO2 to quickly and easily create microservices. Throughout this post, we will see how to use it and take advantage of some of its main features: generation of a REST API, support with Swagger or exception control.
Before we begin, it would be interesting to highlight some of the main ideas of this framework. With its help, our final project will be an auto-deployable JAR file, thanks to the fact that it has an embedded Netty server. But for this, besides having the API REST classes, it will also need to have a root class where we will configure the application and other elements at a global level.
public class Application { public static void main(final String[] args) { new MicroservicesRunner().addExceptionMapper(new ServiceExceptionMapper()).deploy(new BookServiceImpl()) .start(); } }
In the image, we can see how we created an instance of ‘MicroservicesRunner’ that will be the class that will allow us to deploy our project. Through it, we will be able to configure it in one way or another, for example associating a class for exception control such as ‘ServiceExceptionMapper’ or indicating the classes that will contain our API REST, such as ‘BookServiceImpl’.
-This post might interest you! Find out how to apply microservices to a large company-
Now we’ll see the main class, ‘BookServiceImpl’ where we’ll configure our microservice through the following JAX-RS annotations:
- @Path: The path to our API will be indicated. At the class level, it allows us to indicate the root of the route and at method level which is the exact route for each of them.
- @Produces: The format in which the methods will be produced, in this case, JSON, will be determined.
- @GET/@POST/@DELETE/@PUT: With it, besides indicating which HTTP method should be used in conjunction with the path, it will also be possible to access the method.
- @PathParam: It allows us to determine that the value obtained by the input parameter will come as part of the route. Example: /book/1.
- @Context: It will allow us to access the objects ‘Request’ and ‘Response’ of the HTTP call itself along with all its data.
@Path("/book") @Produces(MediaType.APPLICATION_JSON) public class BookServiceImpl implements BookService { Logger LOGGER = LoggerFactory.getLogger(BookServiceImpl.class); private List<Book> list; public BookServiceImpl() { list = new ArrayList<>(); list.add(new Book(1, "Ramon Garrido, Fidel Prieto", "WSO2 Developer's Guide")); list.add(new Book(2, "Prabath Siriwardena", "Enterprise Integration with WSO2 ESB")); } @Override @GET @Path("/{bookId}") public Book getBookById(@PathParam("bookId") final Integer bookId) { return list.get(bookId); } @Override @GET @Path("/list") public List<Book> getList(@Context final Request request) { LOGGER.debug("HttpMethod: " + request.getHttpMethod()); LOGGER.debug("ContentType " + request.getContentType()); return list; } }
In the example we will have two methods that will allow us the following: on the one hand to obtain a concrete book through the method ‘getBookById’; and on the other hand to obtain the complete listing of books through the method ‘getList’, all this through HTTP GET calls.
-Learn everything you need to know about microservices and become an expert-
Now we will see how to create a class that allows us to control the uncontrolled errors of our microservices and return a standard response through the ‘ExceptionMapper’ interface and its ‘toResponse’ method. It is interesting to note that we will be able to do different error checks based on exception types. To do this it is only necessary to indicate which exception we want to control when implementing the ‘ExceptionMapper’ interface. In our case, we will return a 200 code and an ‘Internal server error’ message in JSON format.
public class ServiceExceptionMapper implements ExceptionMapper<Exception> { public class EntityReponse { private String message; public EntityReponse(final String message) { super(); this.message = message; } @Override public String toString() { return "EntityReponse [message=" + message + "]"; } } @Override public Response toResponse(final Exception exception) { return Response.ok(new EntityReponse("Internal server error"), MediaType.APPLICATION_JSON).build(); } }
We should remember that we have previously configured it in the ‘Application’ class.
Finally, we would like to explain how we can give Swagger support to our project. To do this, we only need to include a library as a dependency. This step will also help us to indicate how to configure this project with maven.
-WSO2 ESB Tutorial: Local registry entries, reusable endpoints, and footage-
Globally, our project must inherit from ‘msf4j-service’ through which MSF4J will provide us with all dependencies and internal configuration so that our microservices are ready with just two classes coded. Apart from that, we will add the dependency ‘msf4j-swagger’ to add the Swagger support we request. In principle we would not need anything else for this, just access the following path: ‘http://{server}:{port}/swagger’ once our application is running.
In this path, we will have the scheme and description of our microservice, based on the JAX-RS annotations that we have included.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.wso2.msf4j</groupId> <artifactId>msf4j-service</artifactId> <version>2.6.2</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.chakray.example</groupId> <artifactId>MSF4JExample</artifactId> <version>1.0.0-SNAPSHOT</version> <name>Chakray WSO2 MSF4J Microservice Example</name> <properties> .0 <microservice.mainClass>com.chakray.example.config.Application</microservice.mainClass> </properties> <dependencies> <dependency> <groupId>org.wso2.msf4j</groupId> <artifactId>msf4j-swagger</artifactId> </dependency> </dependencies> </project>
After that, we’d have an idea of how to create a microservice. In order to run it on our premises, we would only have to pack the project with the maven command ‘package’. Then run through the console with the command ‘java -jar MS4JExample-1.0.0-SNAPSHOT.jar’, and to access it from local we would use either of the following two URLs: ‘http://localhost:9090/book/1’ and ‘http://localhost:9090/book/list’. If we want to try the ExceptionMapper we can access the following URL ‘http://localhost:9090/book/0’
Now that you’ve seen how easy it can be to create microservices, it’s time to get down to work. Wait! don’t panic. If you want more advice or help getting started, our team of Chakray experts will be happy to help you, contact us!