springboot自定义事件发布及监听

自定义线程池

@Configuration
public class MyThreadPool {
    //ThreadPoolTaskExecutor不会自动创建ThreadPoolExecutor,需要手动调initialize才会创建。如果@Bean就不需手动,会自动InitializingBean的afterPropertiesSet来调initialize
    @Bean("myExecutor")
    public Executor createJobExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 线程池活跃的线程数
        executor.setCorePoolSize(20);
        // 设置线程队列最大线程数
        executor.setMaxPoolSize(40);
        // 设置等待队列大小
        executor.setQueueCapacity(200);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(60);
        // 线程前缀名称
        executor.setThreadNamePrefix("myExecutor---: ");
        executor.initialize();
        return executor;
    }
}

实体类

public class StudentEvent extends ApplicationEvent{

	private String id;

	private String name;
	
	public StudentEvent(Object source, String id,String name) {
		super(source);
		this.id = id;
		this.name = name;
	}
}

事件发布

sevice层


public interface StudentService {
	 void sendStudentEvent(String id, String name);
}

serviceImpl层

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    ApplicationEventPublisher eventPublisher;
	
	@Override
    @Async("myExecutor")
	public void sendStudentEvent(String id, String name){
		StudentEvent studentEvent = new StudentEvent(this,id,name);
		eventPublisher.publishEvent(studentEvent);
	}
}

事件监听

@Component
public class MyStudentEventListener {

    @EventListener
    @Async("myExecutor")
    public void handleStudentEvent(StudentEvent studentEvent) {
        // 处理事件
    }
}

监听器的执行顺序
如果应用程序中有多个事件监听器,可以通过@Order 注解,指定它们的执行顺序。例如:

@Component
public class MyEventListener1 {

    @EventListener
    @Order(1)
    public void handleEvent(MyEvent event) {
        // 处理事件
    }
}

@Component
public class MyEventListener2 {

    @EventListener
    @Order(2)
    public void handleEvent(MyEvent event) {
        // 处理事件
    }
}

监听器的条件
只想在特定条件下才执行事件监听器,可以使用 @ConditionalOnProperty 注解:

@Component
@ConditionalOnProperty(name = "myapp.event.listener.enabled", havingValue = "true")
public class MyEventListener {

    @EventListener
    public void handleEvent(MyEvent event) {
        // 处理事件
    }
}

参考博客:https://blog.csdn.net/albert_xjf/article/details/131326148

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值