Spring的Event使用及說(shuō)明
1、簡(jiǎn)介
只要是事件就是觀(guān)察者模式,Spring中的Event也不例外,主要應(yīng)用就是程序解耦,實(shí)現(xiàn)本質(zhì)是廣播的形式........話(huà)不多說(shuō)
2、Spring的event實(shí)現(xiàn)方式
繼承ApplicationEvent即可,但是Spring版本4.2之后不再?gòu)?qiáng)制要求繼承ApplicationEvent,非Application的子類(lèi)將被封裝成PayloadApplicationEvent:
實(shí)現(xiàn):
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
//todo -----
private String msg;
public MyEvent(Object source) {
super(source);
}
public MyEvent(Object source,String msg) {
super(source);
this.msg=msg;
}
public String getMsg() {
return msg;
}
}
3、事件的推送
編寫(xiě)事件推送的service實(shí)現(xiàn)ApplicationContextAwar接口,或者實(shí)現(xiàn)ApplicationEventPublisherAware接口,在需要時(shí)候根據(jù)業(yè)務(wù)場(chǎng)景推送事件:
實(shí)現(xiàn):
@Service
public class EventProduceService implements ApplicationContextAware, ApplicationEventPublisherAware {
//實(shí)現(xiàn)方式一
private ApplicationContext applicationContext;
//實(shí)現(xiàn)方式二
private ApplicationEventPublisher applicationEventPublisher;
/**
* 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
* @param applicationEventPublisher
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher=applicationEventPublisher;
}
/**
* 實(shí)際業(yè)務(wù)中進(jìn)行封裝數(shù)據(jù)推送
*/
public void sentEvent(){
//方式一:applicationContext的推送Api可以以根據(jù)需要進(jìn)行選擇
applicationContext.publishEvent(new MyEvent(this,"我是一顆小碼農(nóng)"));
//方式二: applicationEventPublisher的推送Api可以以根據(jù)需要進(jìn)行選擇
applicationEventPublisher.publishEvent(new MyEvent(this,"今天是20220804"));
}
}
4、事件監(jiān)聽(tīng)器(處理器)
編寫(xiě)事件的處理器,交給Spring的ioc管理即可,實(shí)現(xiàn)有兩種方式,
(1)通過(guò)@EventListener注解標(biāo)注對(duì)應(yīng)的事件處理器,處理器會(huì)根據(jù)參數(shù)類(lèi)型自動(dòng)識(shí)別事件類(lèi)型的
實(shí)現(xiàn):
@Configuration
public class EventConfig {
@EventListener
public void doWithEvent(MyEvent myEvent) {
System.out.println("事件消息是: "+myEvent.getMsg());
}
@EventListener
public void doWithEvent(BEvent myEvent) {
System.out.println("事件消息是: "+myEvent.getMsg());
}
@EventListener
public void doWithEvent(CEvent myEvent) {
System.out.println("事件消息是: "+myEvent.getMsg());
}
}(2) 實(shí)現(xiàn)ApplicationListener<T>接口,處理器會(huì)根據(jù)泛型類(lèi)型處理事件
實(shí)現(xiàn)
@Component
public class EventHandler implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
//todo----
System.out.println(event.getMsg());
}
}
5、異步事件
Spring默認(rèn)監(jiān)控的事件都是同步的,實(shí)現(xiàn)異步事件就需要開(kāi)啟異步事件的支持,配置類(lèi)上使用@EventListener注解開(kāi)啟異步支持,然后在監(jiān)聽(tīng)器上使用@Async注解標(biāo)注即可,同一個(gè)事件多個(gè)處理器可以使用@Order注解進(jìn)行排序(參數(shù)越小優(yōu)先級(jí)越高)
實(shí)現(xiàn):
@Configuration
@EnableAsync
public class EventConfig {
@Async
@EventListener
public void doWithEvent(MyEvent myEvent) {
System.out.println("事件消息是: "+myEvent.getMsg());
}
}
@Async//配置類(lèi)已經(jīng)開(kāi)啟異步支持
@Component
public class EventHandler implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
//todo----
System.out.println(event.getMsg());
}
}
6、事件異常處理器(事件消費(fèi)方出現(xiàn)異常進(jìn)行必要處理)
(1) 同步的:
編寫(xiě)異常處理器實(shí)現(xiàn) org.springframework.util.ErrorHandler
import org.springframework.stereotype.Component;
import org.springframework.util.ErrorHandler;
//同步方式異常處理器
@Component
public class DoExphandler implements ErrorHandler {
/**
* 只要在SimpleApplicationEventMulticaster設(shè)置這個(gè)異常處理器,
* 事件消費(fèi)方拋出異常就會(huì)觸發(fā)這個(gè)方法中的異常,SimpleApplicationEventMulticaster.setErrorHandler(exphandler);
*/
@Override
public void handleError(Throwable e) {
if (e instanceof RuntimeException) {
//todo
} else {
}
}
}在SimpleApplicationEventMulticaster事件廣播中設(shè)置消費(fèi)事的異常處理器
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
@Service
public class EventProduceService implements ApplicationContextAware, ApplicationEventPublisherAware {
//實(shí)現(xiàn)方式一
private ApplicationContext applicationContext;
//實(shí)現(xiàn)方式二
private ApplicationEventPublisher applicationEventPublisher;
//事件推送類(lèi)注入廣播處理同步異常
@Autowired
private SimpleApplicationEventMulticaster saem;
@Autowired
private DoExphandler exphandler;
/**
* 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* 容器初始化時(shí)候會(huì)自動(dòng)的填裝該對(duì)象
*
* @param applicationEventPublisher
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void sentEvent2(Object msg) {
applicationContext.publishEvent(new MyEvent2((String) msg));
}
/**
* 設(shè)置初始化的事件異常處理器
*/
@PostConstruct
public void init(){
saem.setErrorHandler(exphandler);
}
}
(2)異步的:
編寫(xiě)異步事件處理器異常類(lèi),實(shí)現(xiàn)AsyncUncaughtExceptionHandler接口
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Component
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable ex,
Method method,
Object... params) {
//todo,做相關(guān)處理
ex.printStackTrace();
}
}
做異步事件異常配置:
實(shí)現(xiàn)AsyncConfigurer接口
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import java.util.concurrent.Executor;
@Configuration
public class AsyncConfig implements AsyncConfigurer {
@Autowired
private AsyncExceptionHandler asyncExceptionHandler;
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return asyncExceptionHandler;
}
@Override
public Executor getAsyncExecutor() {
System.out.println("getAsyncExecutor");
return AsyncConfigurer.super.getAsyncExecutor();
}
}
7、java自帶的事件
(1)觀(guān)察者模式:
- 作用:解耦,解耦....其他都是廢話(huà)
- 模式工作思想:a觀(guān)察b,b做出某些動(dòng)作后,a就及時(shí)的做動(dòng)作的跟進(jìn) (至于a做啥,看你需要他做啥)
- 設(shè)計(jì)思想:a根據(jù)b的狀態(tài)變化做出響應(yīng),一般情況下都是多個(gè)對(duì)象觀(guān)察一個(gè)對(duì)象,此時(shí)被觀(guān)察者b就需要感知到都有哪些對(duì)象在觀(guān)察自己 (設(shè)置集合存儲(chǔ)這些對(duì)象)
- 觀(guān)察者:(在java.util.Observer已經(jīng)做了頂層接口)
public interface MyObserver {
void update(ObserverHandler handler);
}
class MyObserverImp implements MyObserver{
private int status;
/**
* 根據(jù)被觀(guān)察者對(duì)象適應(yīng)自身動(dòng)作
* @param handler 被觀(guān)察者對(duì)象
*/
@Override
public void update(ObserverHandler handler) {
status=((Handler)handler).getStatus();
}
被觀(guān)察者:(java.util. Observable已經(jīng)做了適應(yīng))
interface ObserverHandler {
//存儲(chǔ)觀(guān)察者,感知都有那些對(duì)象在觀(guān)察
List<MyObserver> list = new ArrayList<>();
}
class Handler implements ObserverHandler {
private int status;
public void setStatus(int status) {
this.status = status;
updateAllStatus();
}
public int getStatus() {
return status;
}
public void updateAllStatus() {
for (MyObserver myObserver : list) {
myObserver.update(this);
}
}
public void addObserver(MyObserver observer) {
list.add(observer);
}
public void removeObserver(MyObserver observer) {
list.remove(observer);
}
}(2)java的事件:
創(chuàng)建事件繼承java.util.EventObject
public class UserEvent extends EventObject {
public UserEvent(Object source) {
super(source);
}
}
class SendMessageEvent extends UserEvent {
public SendMessageEvent(Object source) {
super(source);
}
}
class SendFileEvent extends UserEvent {
public SendFileEvent(Object source) {
super(source);
}
}創(chuàng)建事件監(jiān)聽(tīng)器繼承:java.util.EventListener
interface UserListener extends EventListener {
static final ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();
void doWithEvent(UserEvent event);
}
class Listener implements UserListener {
@Override
public void doWithEvent(UserEvent event) {
if (event instanceof SendFileEvent) {
System.out.println(event);
} else if (event instanceof SendMessageEvent) {
System.out.println(event);
}
}
}
推送事件
class SendEventHandler {
private static UserListener listener = new Listener();
public static void main(String[] args) {
final SendMessageEvent sentMessage = new SendMessageEvent("發(fā)送事件");
final SendFileEvent sendFile = new SendFileEvent("發(fā)送文件");
listener.doWithEvent(sentMessage);
listener.doWithEvent(sendFile);
}
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Spring Boot中使用SSE(Server-Sent Events)實(shí)現(xiàn)聊天功能:替代websocket服務(wù)器推送
- SpringBoot實(shí)現(xiàn)SSE(Server-Sent?Events)的完整指南
- 使用Spring Event實(shí)現(xiàn)內(nèi)部模塊間的輕松解耦
- Spring?Boot?整合?SSE(Server-Sent?Events)實(shí)戰(zhàn)案例(全網(wǎng)最全)
- Spring @OnApplicationEvent用法示例小結(jié)(典型用法)
- 解決springboot啟動(dòng)時(shí)報(bào)錯(cuò)的問(wèn)題ApplicationEventMulticaster not initialized
- Java Spring ApplicationEvent 代碼示例解析
相關(guān)文章
用Maven打成可執(zhí)行jar,包含maven依賴(lài),本地依賴(lài)的操作
這篇文章主要介紹了用Maven打成可執(zhí)行jar,包含maven依賴(lài),本地依賴(lài)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08
關(guān)于Java跨域Json字符轉(zhuǎn)類(lèi)對(duì)象的方法示例
這篇文章主要給大家介紹了關(guān)于Java跨域Json字符轉(zhuǎn)類(lèi)對(duì)象的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11
springboot整合jasypt的詳細(xì)過(guò)程
這篇文章主要介紹了springboot整合jasypt的詳細(xì)過(guò)程,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-02-02
js判斷是否是移動(dòng)設(shè)備登陸網(wǎng)頁(yè)的簡(jiǎn)單方法
這篇文章主要介紹了js判斷是否是移動(dòng)設(shè)備登陸網(wǎng)頁(yè)的簡(jiǎn)單方法,需要的朋友可以參考下2014-02-02
SpringBoot集成本地緩存性能之王Caffeine示例詳解
這篇文章主要為大家介紹了SpringBoot集成本地緩存性能之王Caffeine的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
@Configuration與@Component作為配置類(lèi)的區(qū)別詳解
這篇文章主要介紹了@Configuration與@Component作為配置類(lèi)的區(qū)別詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
idea找不到創(chuàng)建package包的選項(xiàng)問(wèn)題及解決方案
在IntelliJ IDEA中找不到創(chuàng)建package包選項(xiàng)?按照步驟操作即可顯示:右鍵選擇Mark Directory as -> Source Root2026-03-03
java接口中的代理設(shè)計(jì)模式代碼時(shí)實(shí)踐
這篇文章主要介紹了java接口中的代理設(shè)計(jì)模式代碼時(shí)實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
詳解Spring Boot使用系統(tǒng)參數(shù)表提升系統(tǒng)的靈活性
Spring Boot項(xiàng)目中常有一些相對(duì)穩(wěn)定的參數(shù)設(shè)置項(xiàng),其作用范圍是系統(tǒng)級(jí)的或模塊級(jí)的,這些參數(shù)稱(chēng)為系統(tǒng)參數(shù)。這些變量以參數(shù)形式進(jìn)行配置,從而提高變動(dòng)和擴(kuò)展的靈活性,保持代碼的穩(wěn)定性2021-06-06

