spring的事件机制实战
生活随笔
收集整理的這篇文章主要介紹了
spring的事件机制实战
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
理論
在分布式場景下,實現同步轉異步的方式有三種方式:
1.異步線程池執行;比如借助@Asyn注解,放到spring自帶的線程池中去執行;
2.放到消息隊列中,在消費者的代碼中異步的消費,執行相關的邏輯;
3.基于spring的事件機制,觸發事件,在監聽器里實現相關邏輯;
spring中自帶了事件的支持,核心類是ApplicationEventPublisher;
事件包括三個要點:下面是一個demo的實現,理論結合實戰。
1 事件的定義;
package com.springbootpractice.demoevent.event;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEvent;/*** @說明 吃飯事件* @作者 carter* @創建時間 2019年07月12日 13:12**/ public class EatEvent extends ApplicationEvent {private static final Logger logger = LoggerFactory.getLogger(EatEvent.class);private Boolean eatFinished;public EatEvent(Boolean eatFinished) {super(eatFinished);this.eatFinished = eatFinished;}public void callGirlFriend() {logger.info("美女,吃完飯了,來收拾一下吧!");}public void callBrothers() {logger.info("兄弟們,吃完飯了,來打dota !");}public Boolean getEatFinished() {return eatFinished;} }2 事件監聽的定義;
package com.springbootpractice.demoevent.event.listener;import com.springbootpractice.demoevent.event.EatEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component;import java.util.Objects;/*** 說明: XEvent的事件監聽器** @author carter* 創建時間 2019年07月12日 13:19**/ @Component public class EatEventListener implements ApplicationListener<EatEvent> {private static final Logger logger = LoggerFactory.getLogger(EatEventListener.class);@Overridepublic void onApplicationEvent(EatEvent xEvent) {if (Objects.isNull(xEvent)) {return;}if (xEvent.getEatFinished()) {xEvent.callGirlFriend();logger.info("xxxx,女朋友拒絕收拾!");xEvent.callBrothers();logger.info("滿人了,下次帶你!");}} }3 發布事件;
package com.springbootpractice.demoevent.web;import com.springbootpractice.demoevent.event.EatEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;/*** 說明 測試控制器** @author carter* 創建時間 2019年07月12日 13:23**/ @RestController public class TestController {private final ApplicationEventPublisher applicationEventPublisher;@Autowiredpublic TestController(ApplicationEventPublisher applicationEventPublisher) {this.applicationEventPublisher = applicationEventPublisher;}@GetMapping(path = "/eatOver")public Object eatOver() {EatEvent xEvent = new EatEvent(true);applicationEventPublisher.publishEvent(xEvent);return "eat over and publish event success";}}無需多余的配置,springmvc直接支持的;
實戰
完整代碼地址
轉載于:https://www.cnblogs.com/snidget/p/11364806.html
總結
以上是生活随笔為你收集整理的spring的事件机制实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 互补色有哪些(互补色配色的方法)
- 下一篇: 问题 1073: 弟弟的作业