1. 程式人生 > >java spring事件機制,釋出訂閱,簡單使用案例

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);

	}

}