Java 使用 EventListener 不是异步问题

2021-04-25 14:18:12 +08:00
 WhiteDragon96

写了个日志异步写入,但是返现监听器里面执行完主线程才会返回
监听器

@Component
public class ApiLogListener {
   private static final Logger log = LoggerFactory.getLogger(ApiLogListener.class);

   @Async
   @Order
   @EventListener({ApiLogEvent.class})
   public void saveLog(ApiLogEvent event) throws InterruptedException {
       Map<String, LogApi> map = (Map<String, LogApi>) event.getSource();
       LogApi logApi = map.get("log");
       System.out.println(logApi);
   }
}

发送是个工具类

@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {

    @Autowired
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
        SpringUtil.context = context;
    }

    /**
     * 发布事件
     *
     * @param event 事件
     */
    public static void publishEvent(ApplicationEvent event) {
        if (context == null) {
            return;
        }
        try {
            context.publishEvent(event);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }
}

我想的是 publishEvent 完就会继续往下走,但是现在需要在 saveLog 结束了才会继续

302 次点击
所在节点    问与答
1 条回复
hexiaowu1993
2021-04-25 15:28:03 +08:00
你是不是没有开启异步。
@EnabledAsync 开启下,另外,@Async 默认的异步只有一个线程,你尽量自己指定下线程池

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/773103

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX