heheyixiao233 2019-04-30 10:05 采纳率: 0%
浏览 6438
已结题

如何在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)

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

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

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

  • 写回答

3条回答

  • 剑小纯 2019-04-30 11:07
    关注
    1. 项目中如果有MQ,在执行主要逻辑后,发送消息到MQ,到时候直接MQ处理执行即可
    2. 项目中没有MQ,请使用线程池,为日志业务单独维护一个线程池,每次执行主要业务逻辑的时候,用该线程池中的线程调用即可.
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败