在开发一个逻辑的过程中,有个插入日志的过程,但插入日志的速度太慢,所以预想让插入日志的过程异步执行,代码类似这样的
执行逻辑
CompletableFuture.runAsync(() -> {
log.info("插入日志");
logService.insert();
});
这相当于是在一个service中,注入了logService,并且执行insert()方法,但这个方法并没有生效(逻辑未执行)
我发现这个方法使用线程实现的,所以我自己写了一个线程来实现,类似于这样
执行逻辑
new Thread(
public void run() {
log.info("插入日志");
logService.insert();
}){}.start()
这次里面的方法倒是执行了,但会报错
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.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.support.WebApplicationContextUtils.currentRequestAttributes(WebApplicationContextUtils.java:309)
at org.springframework.web.context.support.WebApplicationContextUtils.access$400(WebApplicationContextUtils.java:64)
而且方法好像只执行了一半,就好像是主方法已经执行完毕,但线程中的方法没执行完,直接返回了一样...
有没有人有类似的经验,提供一下解法
或者可以解决,一个请求过来,执行方法的主逻辑,主逻辑解决后就返回,其余逻辑在后台执行,类似这样的场景