REST invocation from an event handler

We are working on an application that involves several microservices (Spring Boot) and each of these microservices have their own data-stores.

We are using Axon for CQRS+EventSourcing. Thus, few of the microservices are structured along command-service and query-service.

One of the use-cases involves to call REST api of another microservice from the event-handler of the query service of another microservice.

A-Command-Service (exposes POST /someresource) - This would write to the event store

A-Query-Service - Has an event handler that responds to the above event and updates the query model of A. After this step, we need to make a REST API invocation to B-Command-Service (exposes POST /someotherresrouce)

Apparently, in the event handler, when we are attempting to invoke the REST api (uses OAuth2RestTemplate), we get the below error message:

Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

I have tried defining my own bean (RequestContextListener) but it did not help.

Are there any suggestions / patterns on how I can invoke REST API (via RestTemplate) from within an event handler?

Thanks in advance.

Thanks -


probably, you will need to set some security context indicating the authority for which the event is being handled. A common pattern is to mention the userID (or principal) as a header in each event published as a result of that user’s actions. In an Event handler, you can either set the security context to match that user’s context. An alternative, since it’s not the user’s direct action that’s causing these changes, but a system decision based on an event, it to create a ‘system’ principle, which you set when invoking actions that are triggered by the system itself.

I’m not a Spring Security + OAuth expert, so I don’t know how that is set up for this specific case. In plain Spring Security, you can set the context in the (if I recall correctly) SecurityContextHolder.

Hope this helps.