V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
WhiteDragon96
V2EX  ›  问与答

Java 使用 EventListener 不是异步问题

  •  
  •   WhiteDragon96 · 2021-04-25 14:18:12 +08:00 · 300 次点击
    这是一个创建于 1090 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    @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 结束了才会继续

    hexiaowu1993
        1
    hexiaowu1993  
       2021-04-25 15:28:03 +08:00   ❤️ 1
    你是不是没有开启异步。
    @EnabledAsync 开启下,另外,@Async 默认的异步只有一个线程,你尽量自己指定下线程池
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5193 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 07:37 · PVG 15:37 · LAX 00:37 · JFK 03:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.