spring自定监听器

环境: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这个注解需要在启动的时候开启异步

转载于:https://my.oschina.net/nixi0608/blog/2218790

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值