Spring事件的应用

在项目中为了解耦两个组件,应用了Spring中的事件通知模型。最新的Spring框架可以将任何的实体包装为event,所以,项目中可以发送任何的实体了。

话不多少,直接上代码。

1、事件实体

@Data
@Accessors(chain = true)
@ApiModel("用户审核事件")
public class UserExamineEvent {

    @ApiModelProperty("注册者的id")
    String userId;

    @ApiModelProperty("推荐人的id")
    String recommendId;

    @ApiModelProperty("审核结果")
    boolean success;

    ActivityInfo info;

}

 

2、通知服务

@Service
public class ActivityServiceImpl implements ActivityService, ApplicationEventPublisherAware {
    ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
    @Override
    @Transactional(rollbackFor = {Exception.class, CommonException.class})
    public void examine(ActivityInfo info) {
        int value = activityMapper.examine(info);
        if (value != 1) {
            throw new CommonException(CommonExcepEnums.ERROR.getCode(), "审核失败!");
        }
        final ActivityInfo allInfo = activityMapper.queryByUserId(info);
        boolean isSuccess = "examined".equalsIgnoreCase(info.getStatus()) ? true : false;
        //发送审核操作的事件
        applicationEventPublisher.publishEvent(new UserExamineEvent()
                .setRecommendId(allInfo.getRecommendId())
                .setSuccess(isSuccess)
                .setUserId(allInfo.getUserId().toString())
                .setInfo(allInfo)
        );
}

 

3、事件的监听

@Component
public class UserExamineListener {
@Async
    @EventListener
    public void listenUserExamine(UserExamineEvent event) {
        sendMessage(event);
        if (!event.isSuccess()) return;
        giveRegisterMoney(event);
        Long successed = redisTemplate.opsForValue().increment(getSuccessedKey(event), 1);
        recommendServices.forEach(
                recommendService -> {
                    if (recommendService.isAccept(successed)) {
                        recommendService.afterRecommend(event, successed);
                    }
                }
        );
}
}

 

 

上述代码完成了事件的发送、接收处理等流程。

 

posted @ 2020-05-26 19:18  一家人  阅读(333)  评论(0编辑  收藏  举报