理论知识不多讲,自行度娘。直接上代码,如下。
package com.xx.service.event;
import org.springframework.context.ApplicationEvent;
/**
* @author xuyw
* @version V1.0
* @Description:
* @date 2017-09-11 下午 2:01
*/
public class DmpEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
/**
* 发送事件类型
*/
private EventEnum eventType;
/**
* 发送的消息可发送json字符串
*/
private String msg;
public DmpEvent(Object source, EventEnum eventType, String msg) {
super(source);
this.eventType = eventType;
this.msg = msg;
}
public EventEnum getEventType() {
return eventType;
}
public void setEventType(EventEnum eventType) {
this.eventType = eventType;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public static enum EventEnum {
BIND_EQU("绑定设备"), UNBIND_EQU("解绑设备");
EventEnum(String desc) {
this.desc = desc;
}
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
}
package com.xx.service.event;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.xx.CollectionUtil;
import com.xx.dao.mapper.bo.TEquUserRel;
import com.xx.service.atom.interfaces.ITEquUserRelAtomSV;
import com.xx.service.atom.interfaces.ITEquipmentAtomSV;
/**
@author xuyw
@version V1.0
@Description:
@date 2017-09-11 下午 2:09
*/
@Component
public class DmpListener implements ApplicationListener {
private static final Logger LOG = LogManager.getLogger(DmpListener.class);
@Autowired
ITEquipmentAtomSV iTEquipmentAtomSV;
@Autowired
ITEquUserRelAtomSV iTEquUserRelAtomSV;
@Override
//@Async
public void onApplicationEvent(DmpEvent event) {
DmpEvent.EventEnum eventType = event.getEventType();
String msg = event.getMsg();
LOG.info(“DmpListener收到事件监听:–>”);
LOG.info(“事件类型:” + eventType.getDesc());
LOG.info(“事件内容:” + msg);
switch (eventType) {
case BIND_EQU:
iTEquipmentAtomSV.updateEquBindStatus(msg, “1”);
break;
case UNBIND_EQU:
List list = iTEquUserRelAtomSV
.queryEquUserRelByImei(msg);
if (CollectionUtil.isEmpty(list)) {
// 没有绑定的设备
iTEquipmentAtomSV.updateEquBindStatus(msg, “0”);
}
break;
}
}
}
package com.xx.service.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* @author xuyw
* @version V1.0
* @Description:
* @date 2017-09-11 下午 1:56
*/
@Component
public class DmpPublisher {
@Autowired
ApplicationContext applicationContext;
public void publishDmpEvent(DmpEvent.EventEnum eventType, String msg){
applicationContext.publishEvent(new DmpEvent(this,eventType,msg));
}
}