spring监听器实战

在开发工作中,会遇到一种场景,做完某一件事情以后,需要广播一些消息或者通知,告诉其他的模块进行一些事件处理,一般来说,

可以一个一个发送请求去通知,但是有一种更好的方式,那就是事件监听,事件监听也是设计模式中 发布-订阅模式。

观察者模式实现

1、事件(event)可以封装和传递监听器中要处理的参数,如对象或字符串,并作为监听器中监听的目标。

2、监听器(listener)具体根据事件发生的业务处理模块,这里可以接收处理事件中封装的对象或字符串。

3、事件发布者(publisher)事件发生的触发者。

本监听器不适合跨系统,如果跨系统需配合消息一起处理。

1.创建一个监听器的对象

继承ApplicationEvent并且提供get方法

/**
 * 会员数据事件参数
 * @author  ywl
 * @date 2018-05-14
 */
public class MemberAnalyseMsgParamBean  extends ApplicationEvent implements Serializable {

    /** 会员id **/
    private String memberId;
    /** 类型 1:注册 2:绑卡 3:充值 4:交易 **/
    private Integer  type;
    /** 会员渠道id **/
    private String channelId;

    public MemberAnalyseMsgParamBean(Object source, String memberId, Integer type) {
        super(source);
        this.memberId = memberId;
        this.type = type;
    }


    public String getMemberId() {
        return memberId;
    }
    public Integer getType() {
        return type;
    }
    public String getChannelId() {
        return channelId;
    }
}

2.实现监听

@Component
public class MemberAnalyseListener implements ApplicationListener<MemberAnalyseMsgParamBean> {

    private static Logger logger = LoggerFactory.getLogger(MemberAnalyseListener.class);

    @Override
    public void onApplicationEvent(MemberAnalyseMsgParamBean paramBean) {
        logger.info("-------开始统计了-------");
        logger.info("-------memberId-------"+paramBean.getMemberId());
        logger.info("---------type-----"+paramBean.getType());
    }
}

3.发布监听消息

/**
 * 会员数据发布
 */
@Component
public class MemberAnalysePublish  implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext  = applicationContext;
    }

    public void memberAnalysePublish(String memberId,Integer type){
        MemberAnalyseMsgParamBean memberAnalyseEventParamBean = new MemberAnalyseMsgParamBean(this, memberId, type);
        applicationContext.publishEvent(memberAnalyseEventParamBean);
    }
}

4.使用监听

@RunWith(SpringRunner.class)
@SpringBootTest
public class AnalyseServiceApplicationTests {

   @Resource
   private MemberAnalysePublish memberAnalysePublish;

   @Test
   public void contextLoads() {
      memberAnalysePublish.memberAnalysePublish("100001",1);
   }

}

猜你喜欢

转载自blog.csdn.net/qq_39291929/article/details/80310629