关于Spring事件驱动使用及注意

Spring事件驱动组成

Spring事件驱动由3个部分组成:

1、ApplicationEvent:表示事件本身,自定义事件需要继承该类。用来定义事件

2、ApplicationEventPublisherAware:事件发送器,需要实现该接口。主要用来发布事件.ApplicationContext 也实现了该接口,可以用于发布事件.

Spring4.2之后,ApplicationEventPublisher自动被注入到容器中,采用Autowired即可获取。

3、ApplicationListener:事件监听器接口。监听类实现ApplicationListener 里onApplicationEvent方法即可.

在spring4.2以后我们可以以更加简洁的方式来监听event的发布,监听事件我们不必再实现ApplicationListener接口了,只要在方法上添加注解@EventListener即可.

使用步骤

Spring中使用事件非常简单,只需要以下的几个步骤:

  1. 定义事件,继承ApplicationEvent
    /** 积分事件驱动
     * @Description: 积分事件驱动
     * @Author:  admin
     * @Date: 2023/9/12 16:58
     */
    public class OperateStockIntegralEvent extends ApplicationEvent {
        public OperateStockIntegralEvent(Object source) {
            super(source);
        }
    }
  2. 定义监听,要么实现ApplicationListener接口,要么在方法上添加@EventListener注解
    @Component
    @Slf4j
    public class OperateEventListener {
    
        @Resource
        private ISendMessageService sendMessageService;
    
    
        @EventListener
        @Async(AsyncNameConstant.BASE_ASYNC_NAME_EXECUTOR)
        public void OperateStockIntegral(OperateStockIntegralEvent operateStockIntegralEvent) {
            OperateStockIntegralDTO stockIntegralDTO = (OperateStockIntegralDTO)         operateStockIntegralEvent.getSource();
            log.info("-----------操作积分事件驱动的逻辑------------" + JSONObject.toJSONString(stockIntegralDTO));
            try {
                //发MQ消息赠送积分
                sendMessageService.sendStockIntegralMQ(stockIntegralDTO);
            } catch (Exception e) {
                log.error("积分操作失败", e);
            }
        }
    }
  3. 发布事件,调用ApplicationContext.publishEvent()或者ApplicationEventPublisher.publishEvent();
@Service("subOrderService")
@Slf4j
public class SubOrderServiceImpl extends BaseServiceImpl<SubOrderMapper, SubOrderDomain> implements ISubOrderService {  

@Resource
private ApplicationEventPublisher applicationEventPublisher;

 @Override
 public R<Object> buyProductGiveStockIntegral(SubOrderDomain suborder) {
    OperateStockIntegralDTO stockIntegralDTO = new OperateStockIntegralDTO();
    //用户id
    stockIntegralDTO.setUserId(suborder.getUserId());
    //订单id
    stockIntegralDTO.setObjectId(relationId);     
    applicationEventPublisher.publishEvent(new OperateStockIntegralEvent(stockIntegralDTO));
    return R.ok();

    }


}

@TransactionalEventListener有一个属性为fallbackExecution,默认为false,指发布事件的方法没有事务控制时,监听器不进行监听事件,此为默认情况!fallbackExecution=true,则指发布事件的方法没有事务控制时,监听方法仍可以监听事件进行处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值