Asynchronous event publishing with Spring Boot

Ladies & gents, I’ve created sample Spring Boot app that demonstrates useful scenario of asynchronous publish / subscribe model. It could be useful in many ways. Idea is that, for example, you have some API handling some web requests, and apart from functionality it provides, it also publishes some event, so that some other thread can react upon it, with main functionality still being processed with request handling thread. Or even shorter – request handling thread will do it’s job, and publishes some event (using Java annotation), and some other background thread will subscribe to event and process it. You can use it for scenario you register user with your API, and publish user registered event, and in background you can subscribe to it by sending out e-mail to end user.

You can checkout source code from GitHub

Easiest way to start your application could be running it via spring-boot:run Maven goal:

mvn spring-boot:run

That will start our demo app on standard 8080 port.

Demo app contains two APIs, get user and update user. Those are just dummy implementations. It also has User domain model class.

You can then, using command line and curl tool, issue the get user request (I’m just doing pipe to jq tool  for nicer response rendering – you can omit that part):

curl -s 'http://localhost:8080/users/1' | jq .
 "id": 1,
 "age": 33,
 "name": "Some name"
2017-04-23 11:46:59.940 INFO 7421 --- [nio-8080-exec-1] de.odalinho.async.PublishingController : PublishingController::Thread.currentThread().getName() = http-nio-8080-exec-1
2017-04-23 11:46:59.941 INFO 7421 --- [pool-1-thread-3] d.o.a.m.UserNotificationPublisher : UserNotificationPublisher::Thread.currentThread().getName() = pool-1-thread-3
2017-04-23 11:46:59.941 INFO 7421 --- [pool-1-thread-3] d.o.a.m.UserNotificationPublisher : UserNotificationPublisher::event.getMessage() = User(id=1, age=33, name=Some name)

Continue reading