loading...

January 27, 2019

autobahn-spring – Integration of 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 @ControllerTopics 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.

public WampController() {

    this.executor = Executors.newSingleThreadExecutor();
    this.session = new Session(executor);

    session.addOnJoinListener(this::registerExample);
    session.addOnJoinListener(this::callExample);
    session.addOnJoinListener(this::subscribeExample);
    session.addOnJoinListener(this::publishExample);
}

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.

@PostConstruct
public void start() {

    Client client = new Client(session, url, realm, executor);
    try {
        client.connect().get();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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.

@SpringBootApplication
public class AutobahnSpringApplication {

    public static void main(String[] args) {
        SpringApplication.run(AutobahnSpringApplication.class, args);
    }
}

To see the whole project, have a look at my GitHub page.

Posted in Java, Spring, WAMPTaggs: