Article
autobahn-spring: Autobahn|Java and Spring
Are you an enthusiastic user of Spring and do you also want to benefit from the Web Application Messaging Protocol? Even though wamp2spring mainly serves as a router, Spring users often want to create several microservices communicating with each other. A comfortable solution is using the WAMP library Autobahn|Java. This article will describe how to combine Spring and Autobahn|Java.
Create a Controller for WAMP
Autobahn|Java could be implemented as a controller. Therefore, the bean of Spring should be created with the annotation @Controller. Topics and procedures could be handled exactly as described in the article about Autobahn|Java. The methods implementing this should be registered as listeners. This could be achieved in the constructor of the controller.
1public WampController() {
2
3 this.executor = Executors.newSingleThreadExecutor();
4 this.session = new Session(executor);
5
6 session.addOnJoinListener(this::registerExample);
7 session.addOnJoinListener(this::callExample);
8 session.addOnJoinListener(this::subscribeExample);
9 session.addOnJoinListener(this::publishExample);
10}
The main difference between using the raw Jetty-based library and implementing Autobahn|Java as a Spring bean is that the controller starts automatically after the object gets created. In Spring, this could be realised with the annotation @PostConstruct. A method annotated like this gets executed automatically after the object gets instantiated. This method for starting the controller would try to connect to the router.
1@PostConstruct
2public void start() {
3
4 Client client = new Client(session, url, realm, executor);
5 try {
6 client.connect().get();
7 } catch (Exception e) {
8 e.printStackTrace();
9 }
10}
Run the Application
To run the whole application, the main method and the annotation @SpringBootApplication have to be added. This could be done either in the same class or in a separate one.
1@SpringBootApplication
2public class AutobahnSpringApplication {
3
4 public static void main(String[] args) {
5 SpringApplication.run(AutobahnSpringApplication.class, args);
6 }
7}
To see the whole project, have a look at my GitHub page.