简体   繁体   中英

How to create unique Id per request for REST API in Spring-boot?

I need to make my logs (log4j engine) to be more informative with a unique id per request for my REST API in Spring-Boot application.

I want to avoid using a superclass which got requestId field and extend from it.

I tried to look for a good example over the web, but it wasn't so clear.

Is there any best practice that I can use?

Using a field for such a feature would just cause problems during the integration testing on the first glance..

Ideally, just follow an SRP principle and include the generation logic inside a dedicated class which you could make an injectable @Component .. MyIdGenerator etc.

There you could have a synchronized method generateId() .

Now you could use it in whichever controller it is needed and also you could set-up your integration test more easily and have more control over them.

Update:

You could take also advantage of HandleInterceptorAdapter if this should be a global strategy:

@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

    /* generate unique id here and log what is needed */

    }

You can encapsulate the ID generation and logging inside this class.

There are several best practices used as follows:

  1. Use AOP Refer : AOP used for controller layer
  2. Use MDC
  3. Use MDC with AOP MDC with AOP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM