如何在service层中,进行异步操作?为什么CompletableFuture.runAsync这个方法调用的方法没执行?

在开发一个逻辑的过程中,有个插入日志的过程,但插入日志的速度太慢,所以预想让插入日志的过程异步执行,代码类似这样的

执行逻辑
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)

而且方法好像只执行了一半,就好像是主方法已经执行完毕,但线程中的方法没执行完,直接返回了一样...

有没有人有类似的经验,提供一下解法

或者可以解决,一个请求过来,执行方法的主逻辑,主逻辑解决后就返回,其余逻辑在后台执行,类似这样的场景

  1. 项目中如果有MQ,在执行主要逻辑后,发送消息到MQ,到时候直接MQ处理执行即可
  2. 项目中没有MQ,请使用线程池,为日志业务单独维护一个线程池,每次执行主要业务逻辑的时候,用该线程池中的线程调用即可.

是不是没有开启异步线程?
如果是springboot在启动类加入@EnableAsync

或者你贴更详细的代码过来,单纯这个开启线程执行看不出什么问题。

错误消息的意思是你在新的线程中调用了request scope里的东西,应该是在logService里有引用。
这种情况下需要先把logService跟http request隔离开