spring事件使用

定义事件

import lombok.Data;
import org.springframework.context.ApplicationEvent;

@Data
public class TransferPenaltyEvent extends ApplicationEvent {
    private String billCode;

    public TransferPenaltyEvent(String billCode) {
        super(billCode);
        this.billCode = billCode;
    }
}

发事件

@Autowired
private ApplicationContext applicationContext;
applicationContext.publishEvent(new TransferPenaltyEvent(realScanMsg.getBillCode()));

监听事件

/**
  * 监听开始结算事件
  */
 @EventListener(TransferPenaltyEvent.class)
 public void penalty(TransferPenaltyEvent event) {
     try {
         //末中心判罚主逻辑
         transferPenaltyBiz.handle(event.getBillCode());
         //冷链判罚处理
         penaltyColdChain(event.getBillCode());
     } catch (Exception e) {
         log.error("中心判罚错误,billCode={}", event.getBillCode(), e);
     }
 }

spring事件默认是同步的,通过启动类Application上加@EnableAsync 开启异步,使用方法注解@Async可以是方法异步执行。@Async不带参数默认使用springBoot默认线程池。推荐使用自定义线程池,如:@Async(“executor”)

@Configuration
public class ThreadPoolConfig {

    @Bean("executor")
    public Executor getExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,
                20,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue(10000));
        return executor;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值