【匯智學堂】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);

	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章