Spring/Spring boot中使用自定义事件监听

在实际开发过程中,常常遇到这种场景: 
做完某一件事情以后,需要广播一些消息或者通知,告诉其他的模块进行一些事件处理,一般来说,可以一个一个发送请求去通知,但是有一种更好的方式,那就是事件监听,事件监听也是设计模式中 发布-订阅模式、观察者模式的一种实现。

观察者模式:在对象之间定义了一对多的依赖,这样一来,当一个对象改变状态,依赖它的对象会收到通知并自动更新。

Spring的事件为Bean和Bean之间的消息传递提供支持。当一个对象处理完某种任务后,通知另外的对象进行某些处理,常用的场景有进行某些操作后发送通知,消息、邮件等情况。 
Spring提供5种标准的事件监听:

  1. 上下文更新事件(ContextRefreshedEvent):该事件会在ApplicationContext被初始化或者更新时发布。也可以在调用ConfigurableApplicationContext接口中的refresh()方法时被触发。
  2. 上下文开始事件(ContextStartedEvent):当容器ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
  3. 上下文停止事件(ContextStoppedEvent):当容ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
  4. 上下文关闭事件(ContextClosedEvent):当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
  5. 请求处理事件(RequestHandledEvent):在Web应用中,当一个http请求(request)结束触发该事件。

不过也有些实际场景并用不上框架提供的标准事件,这个时候我们就需要自定义事件监听 
Spring的事件遵循的流程:

  1. 自定义事件,继承ApplicationEvent(org.springframework.context.ApplicationEvent)
  2. 定义监听事件,实现ApplicationListener(org.springframework.context.ApplicationListener)
  3. 使用容器触发事件

Spring中书写事件监听有两种方式,编程式和注解式,这里两种都进行简单的说明。因为现在正好在看boot方面的东西,这里就以boot项目为基础开启事件监听,boot也是spring全家桶的一部分,所以配置和使用和传统spring项目也没什么区别,当然,boot提倡无xml,所以这里开启监听的方式也用注解的方式进行。

一:自定义事件

package com.cnjy.ecampus.modules.cms.domain;
import org.springframework.context.ApplicationEvent;

import com.cnjy.ecampus.modules.um.domain.User;

/**
 * 自定义监听方法类
 */
public class ListenerRabbitEvent extends ApplicationEvent{


	/**
	 * 操作对象 可以是对应的list
	 */
	private Object operationObj;
	/*
	 * 发送类型 add update delete
	 */
	private String sendType;
	/**
	 * 类型  class student teacher users
	 */
	private String type;
	/**
	 * 提示信息
	 */
	private String hitMsg;
	/**
	 * 登录用户
	 */
	private User loginUser;
	

    /**
     * 在自定义事件的构造方法中除了第一个source参数,其他参数都可以去自定义,
     * 可以根据项目实际情况进行监听传参,这里就只定义个简单的String字符串的透传
     * @param source
     * @param operationObj sendType type hitMsg loginUser
     */
    public ListenerRabbitEvent(Object source, Object operationObj, String sendType, String type
    		, String hitMsg, User loginUser) {
        super(source);
        this.operationObj = operationObj;
        this.sendType = sendType;
        this.type = type;
        this.hitMsg = hitMsg;
        this.loginUser = loginUser;
    }


	public Object getOperationObj() {
		return operationObj;
	}


	public void setOperationObj(Object operationObj) {
		this.operationObj = operationObj;
	}


	public String getSendType() {
		return sendType;
	}


	public void setSendType(String sendType) {
		this.sendType = sendType;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}


	public String getHitMsg() {
		return hitMsg;
	}


	public void setHitMsg(String hitMsg) {
		this.hitMsg = hitMsg;
	}


	public User getLoginUser() {
		return loginUser;
	}


	public void setLoginUser(User loginUser) {
		this.loginUser = loginUser;
	}

    /**
     * 自定义监听器触发的透传打印方法
     * @param msg
     */
//    public void printMsg(String msg)
//    {
//        System.out.println("编程事件监听:" + msg);
//    }


}

二:事件监听

package com.cnjy.ecampus.ribbitmq;
import javax.annotation.Resource;
import javax.inject.Qualifier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.cnjy.ecampus.framework.util.LogUtils;
import com.cnjy.ecampus.modules.cms.domain.ListenerRabbitEvent;

/**
 * 测试用自定义监听器,监听事件为MyEvent
 */
@Component
public class LisenterRabbitMsg implements ApplicationListener<ListenerRabbitEvent>{

	@Resource
	private RibbitManage ribbitManage;
    /**
     * 对监听到的事件进行处理
     * @param myEvent
     */
    @Override
    public void onApplicationEvent(ListenerRabbitEvent listenerRabbitEvent) {

    	LogUtils.info("=====================已经监听到并执行处理监听后的逻辑(此处根据自己业务不同进行不同的处理)=======================");
    	//发送ribbit消息
		boolean result = ribbitManage.sendRibbitMsg(listenerRabbitEvent.getOperationObj(), listenerRabbitEvent.getSendType(),
				listenerRabbitEvent.getType(), listenerRabbitEvent.getHitMsg(), listenerRabbitEvent.getLoginUser());
		if (!result) {
			LogUtils.info("发送ribbit消息失败---------------------------" );
			LogUtils.info("sendType=" + listenerRabbitEvent.getSendType() + ",="  + listenerRabbitEvent.getType() 
					+ ",hitMsg=" + listenerRabbitEvent.getHitMsg());
		}
    	
      
    }
    
    
}

三:事件发布

package com.cnjy.ecampus.modules.cms.service;

import com.cnjy.ecampus.modules.um.domain.User;

public interface ListenerRabbitService{
    public void publish(Object operationObj, String sendType, String type
    		, String hitMsg, User loginUser);
}
package com.cnjy.ecampus.modules.cms.service;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.cnjy.ecampus.framework.util.LogUtils;
import com.cnjy.ecampus.modules.cms.domain.ListenerRabbitEvent;
import com.cnjy.ecampus.modules.um.domain.User;

import javax.annotation.Resource;

@Service("listenerRabbitService")
public class ListenerRabbitServieImpl implements ListenerRabbitService{

    /**
     *  上下文对象
     */
    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void publish(Object operationObj, String sendType, String type
    		, String hitMsg, User loginUser) {

    	LogUtils.info("--发布监听");
        //通过上下文对象发布监听
        applicationContext.publishEvent(new ListenerRabbitEvent(this,operationObj, sendType, type,
        		hitMsg, loginUser));
    }
}

测试类入口

package com.cnjy.ecampus.listen;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cnjy.ecampus.modules.cms.service.ListenerRabbitService;
import com.cnjy.ecampus.modules.um.domain.User;

/**
 * 事件监听测试
 */
@RestController
public class listenerTest  {

    @Resource
    private ListenerRabbitService listenerRabbitService;
    
    @RequestMapping("/listen/test")
    public void testEvent()
    {
    	System.out.println("------------");
    	//此处发布监听
    	Object obj = "obj";
    	User loginUser = new User();
    	listenerRabbitService.publish(obj, "add", "users", "需要添加的用户", loginUser);
    }
}



java 技术交流群:317628801



猜你喜欢

转载自blog.csdn.net/qq_33545491/article/details/80924639