spring的事件机制实战
生活随笔
收集整理的這篇文章主要介紹了
spring的事件机制实战
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
理論
在分布式場(chǎng)景下,實(shí)現(xiàn)同步轉(zhuǎn)異步的方式有三種方式:
1.異步線程池執(zhí)行;比如借助@Asyn注解,放到spring自帶的線程池中去執(zhí)行;
2.放到消息隊(duì)列中,在消費(fèi)者的代碼中異步的消費(fèi),執(zhí)行相關(guān)的邏輯;
3.基于spring的事件機(jī)制,觸發(fā)事件,在監(jiān)聽器里實(shí)現(xiàn)相關(guān)邏輯;
spring中自帶了事件的支持,核心類是ApplicationEventPublisher;
事件包括三個(gè)要點(diǎn):下面是一個(gè)demo的實(shí)現(xiàn),理論結(jié)合實(shí)戰(zhàn)。
1 事件的定義;
package com.springbootpractice.demoevent.event;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEvent;/*** @說明 吃飯事件* @作者 carter* @創(chuàng)建時(shí)間 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 事件監(jiān)聽的定義;
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的事件監(jiān)聽器** @author carter* 創(chuàng)建時(shí)間 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 發(fā)布事件;
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;/*** 說明 測(cè)試控制器** @author carter* 創(chuàng)建時(shí)間 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直接支持的;
實(shí)戰(zhàn)
完整代碼地址
轉(zhuǎn)載于:https://www.cnblogs.com/snidget/p/11364806.html
總結(jié)
以上是生活随笔為你收集整理的spring的事件机制实战的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 互补色有哪些(互补色配色的方法)
- 下一篇: 问题 1073: 弟弟的作业