我是靠谱客的博主 悦耳缘分,最近开发中收集的这篇文章主要介绍【四二学堂】java spring事件机制,发布订阅,简单使用案例,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

spring配置文件添加


<!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->
<task:executor id="executor" pool-size="10"/> <task:scheduler id="scheduler" pool-size="10"/>
<task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>

 业务中调用(发布事件)

//保存历史记录(使用场景)
//发布事件
String content = "用户-"+user.getName()+"-对本条数据-"+info.getNum()+"-进行了修改操作";
//对象转json存入数据库 业务需要
String json = JsonUtil.objectToJsonStr(info);
//BusLog是自己定义的一个日志类
applicationEventPublisher.publishEvent(new BusLogEvent(new BusLog(info.getId(),info.getCode(),user.getOffice().getId(),content,json,"info_log"),request));

定义event类(集成ApplicationEvent 类)

/**
* 设备的事件
*/
public class BusLogEvent extends ApplicationEvent {
//业务需要,可不传
public HttpServletRequest request;
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
//自定义构造方法
public BusLogEvent(Object source, HttpServletRequest request) {
super(source);
this.request = request;
}
//必须有
public BusLogEvent(BusLog source) { //name即source
super(source);
}
}

事件监听器(@Async注解代表是异步执行)

可在多个地方发布事件,一个地方消费

@Component
public class BusLogEventListener {
@Autowired
private BusLogService busLogService;
@Async
@EventListener
public void onApplicationEvent(BusLogEvent deviceEvent) {
System.out.println("-------------------------事件消费者执行-------------------------------------");
HttpServletRequest request = deviceEvent.getRequest();
String remoteAddr = StringUtils.getRemoteAddr(request);
BusLog busLog = (BusLog) deviceEvent.getSource();
busLog.setFdRemoteAddr(remoteAddr);
busLogService.save(busLog);
}
}

 

最后

以上就是悦耳缘分为你收集整理的【四二学堂】java spring事件机制,发布订阅,简单使用案例的全部内容,希望文章能够帮你解决【四二学堂】java spring事件机制,发布订阅,简单使用案例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部