zoukankan      html  css  js  c++  java
  • spring事件机制(多线程异步监听事件)

    上一篇添加了基础的时间监听机制

    异步实现事件的监听:
    注意上面的ApplicationListener 中的监听机制为同步执行,即若发布两个事件,则必须等待前一个事件完成才能继续执行下一个事件,这里可以通过

    spring的异步机制来实现:spring3.0版本开始支持@Async注解来实现异步调用。

    新建一个线程配置类,此处两点必须@EnableAsync注解和spring内置线程池ThreadPoolTaskExecutor:

    @Configuration
    @EnableAsync
    public class ListenerAsyncConfiguration implements AsyncConfigurer
    {
        /**
         * 获取异步线程池执行对象
         * @return
         */
        @Override
        public Executor getAsyncExecutor() {
            //使用Spring内置线程池任务对象
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            //设置线程池参数
            taskExecutor.setCorePoolSize(5);//核心池大小
            taskExecutor.setMaxPoolSize(10);//最大线程数
            taskExecutor.setQueueCapacity(25);//队列程度
            taskExecutor.setKeepAliveSeconds(100);//空闲时间
            taskExecutor.setThreadNamePrefix("Thread_Test");//线程前缀名称
            taskExecutor.initialize();
            return taskExecutor;
        }
    
        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return null;
        }
    }

    监听器中添加@Async注解:

    @Component
    public class UserRegisterEventListener implements ApplicationListener<UserRegisterEvent> {
        @Override
        @Async
        public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
            try {
                Thread.sleep(1000);//静静的沉睡3秒钟
            }catch (Exception e)
            {
                e.printStackTrace();
            }
            System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
            System.out.println(String.format("接口模式给用户[%S]发送邮件成功",userRegisterEvent.getUserName()));
        }
    }
  • 相关阅读:
    [做题记录-乱做] [AGC004F] Namori
    字符串分割去除空格
    逆向实战01-嘟嘟牛在线
    mysql超8小时解决
    macbook golang的debug模式不好使
    博客暂时废弃公告
    [干货] 博客园主题
    [Contest on 2021.10.14] 我靠,真的好困!
    [Contest on 2021.10.9] 说好的 100kb 呢?
    [Contest on 2021.10.7] 已经起不了标题了...
  • 原文地址:https://www.cnblogs.com/mangwusuozhi/p/15479252.html
Copyright © 2011-2022 走看看