环境:spring-boot-1.5.8,JDK1.8
- 自定义事件
/**
* @author
* @Description:
* 钱包业务通知事件
* @date 2018/9/27
*/
public class AccountNotifyEvent extends ApplicationEvent {
private static final long serialVersionUID = -1492555537413218746L;
/**
* 事件通知参数
*/
private AccountNotifyEventParam accountNotifyEventParam;
public AccountNotifyEvent(Object source,AccountNotifyEventParam accountNotifyEventParam){
super(source);
this.accountNotifyEventParam = accountNotifyEventParam;
}
public AccountNotifyEventParam getAccountNotifyEventParam() {
return accountNotifyEventParam;
}
}
- 自定义监听器
/**
* @author
* @Description:
* 事件监听
* @date 2018/9/27
*/
@Component
public class AccountNotifyApplicationListener implements ApplicationListener<AccountNotifyEvent> {
private static final Logger logger = LoggerFactory.getLogger(AccountNotifyApplicationListener.class);
@Autowired
private IAccountService accountService;
/**
* 监听事件,异步处理相关的事件
* @param event the event to respond to
*/
@Override
@Async
public void onApplicationEvent(AccountNotifyEvent event) {
logger.info("事件来源:{},参数:{}",event.getSource(),JSON.toJSONString(event.getAccountNotifyEventParam()));
AccountNotifyEventParam notifyEventParam = event.getAccountNotifyEventParam();
if(notifyEventParam == null){
logger.error("事件参数为空,来源:{}",event.getSource());
return;
}
AccountNotifyBusinessTypeEnum businessTypeEnum = AccountNotifyBusinessTypeEnum.valueOfCode(notifyEventParam.getBusinessType());
if(businessTypeEnum == null){
logger.error("暂不支持该种业务,来源:{}",event.getSource());
}
//处理相应的事件
switch (businessTypeEnum){
case UPDATE_AMOUNT:
logger.info("更新账户,accountId:{}",notifyEventParam.getAccountId());
accountService.updateFuiouAmountByAccountId(notifyEventParam.getAccountId());
break;
default:
break;
}
}
}
- 使用
AccountNotifyEventParam accountNotifyEventParam = new AccountNotifyEventParam();
accountNotifyEventParam.setAccountId(1306L);
accountNotifyEventParam.setBusinessType(AccountNotifyBusinessTypeEnum.UPDATE_AMOUNT.getCode());
AccountNotifyEvent accountNotifyEvent = new AccountNotifyEvent("测试更新",accountNotifyEventParam);
applicationContext.publishEvent(accountNotifyEvent);
PS:@Async这个注解需要在启动的时候开启异步