zoukankan      html  css  js  c++  java
  • 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);
                        }
                    }
            );
    }
    }

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

  • 相关阅读:
    iframeWin For Easy UI. 为 Easy UI 扩展的支持IFrame插件
    mac系统及xcode使用的SVN客户端安装升级
    泛型List的一点建议
    redis-setbit理解
    zpkin sql语句
    idea 使用 RunDashboard启动
    (转)Spring事务不生效的原因大解读
    (转)Lock和synchronized比较详解
    springboot整合HttpAsyncClient简单实用
    mysql 数据库表迁移复制
  • 原文地址:https://www.cnblogs.com/sunxianbiao/p/12967832.html
Copyright © 2011-2022 走看看