定义事件
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;
}
}