SpringBoot實現(xiàn)事件監(jiān)聽(異步執(zhí)行)的示例代碼
在Spring Boot中,事件監(jiān)聽是一種機制,通過該機制,你可以定義和觸發(fā)自定義的事件,以及在應用程序中注冊監(jiān)聽器來響應這些事件,提供了一種解耦的方式來處理應用程序中的事件。
事件監(jiān)聽的主要組件包括:
事件(Event):
- 事件是一個普通的Java對象,用于封裝與應用程序中發(fā)生的某個動作或狀態(tài)變化相關的信息。
事件發(fā)布器(Event Publisher):
- 事件發(fā)布器是一個負責將事件發(fā)布給注冊的監(jiān)聽器的組件。在Spring中,
ApplicationEventPublisher接口定義了事件發(fā)布器的標準。
- 事件發(fā)布器是一個負責將事件發(fā)布給注冊的監(jiān)聽器的組件。在Spring中,
事件監(jiān)聽器(Event Listener):
- 事件監(jiān)聽器是用于監(jiān)聽和響應特定事件的組件。在Spring中,通過
ApplicationListener接口或使用@EventListener注解來定義事件監(jiān)聽器。
在Spring Boot中實現(xiàn)事件監(jiān)聽的步驟如下:
定義事件類:
- 創(chuàng)建一個普通的Java類,用于表示特定的事件。該類通常繼承自
ApplicationEvent或其子類。
定義事件發(fā)布器(可選):
- 可以在需要的地方注入
ApplicationEventPublisher并使用它來發(fā)布事件,或者直接通過Spring容器(ApplicationContext)發(fā)布事件。
定義事件監(jiān)聽器:
- 創(chuàng)建一個實現(xiàn)
ApplicationListener接口或使用@EventListener注解的類,用于監(jiān)聽特定的事件,并在事件發(fā)生時執(zhí)行相應的邏輯。
注冊監(jiān)聽器:
- 將事件監(jiān)聽器注冊到Spring容器中,可以通過注解、Java配置或XML配置來完成。
以下是一個簡單的示例,演示了如何在Spring Boot中實現(xiàn)事件監(jiān)聽(主要代碼展示):
代碼層級結構:

1.自定義事件類 CoursesTestEvent繼承ApplicationEvent:
package com.example.springbootredis.event;
import lombok.Getter;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;
/**
* 課程事件類,繼承自 ApplicationEvent,表示課程相關的事件。
*/
@Setter
@Getter
public class CoursesTestEvent extends ApplicationEvent {
private Integer id;
/**
* 課程標題
*/
private String title;
/**
* 課程封面
*/
private String thumb;
/**
* 課程價格(分)
*/
private Integer charge;
/**
* 隨便傳遞幾個參數(shù)
* */
public CoursesTestEvent(Object source, String title, String thumb) {
super(source);
this.title = title;
this.thumb = thumb;
}
}
2.創(chuàng)建一個事件監(jiān)聽器類 CoursesTestListener:
package com.example.springbootredis.listener;
import com.example.springbootredis.event.CoursesTestEvent;
import com.example.springbootredis.service.CoursesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* 用于測試監(jiān)聽事務,異步執(zhí)行方法
* 課程事件監(jiān)聽器類,用于異步更新課程信息。
*/
@Component
@Slf4j
public class CoursesTestListener {
//根據(jù)實際的需求進行注入
@Autowired
private CoursesService coursesService;
/**
* 異步事件監(jiān)聽方法,用于監(jiān)聽CoursesTestEvent進行更新課程相關信息。
* @param event 觸發(fā)的課程的事件。
*/
// @Async("myTaskExecutor") // 異步執(zhí)行的注解,線程池
// @Async() // 異步執(zhí)行的注解
@EventListener // 事件監(jiān)聽器的注解
public void updateLoginInfo(CoursesTestEvent event) {
//檢查是否能夠獲取到CoursesTestEvent
System.out.println("title:"+event.getTitle());
System.out.println("thumb:"+event.getThumb());
System.out.println(3);
// 打印當前線程的信息
System.out.println("執(zhí)行當前線程的名稱3: " + Thread.currentThread().getName());
}
}
3.在業(yè)務邏輯中進行測試事件監(jiān)聽:
package com.example.springbootredis.service.impl;
import com.example.springbootredis.domain.Courses;
import com.example.springbootredis.event.CoursesTestEvent;
import com.example.springbootredis.mapper.CoursesMapper;
import com.example.springbootredis.service.CoursesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class CoursesServiceImpl implements CoursesService {
@Autowired
private CoursesMapper coursesMapper;
//用于管理和維護Bean以及處理Bean之間依賴關系的核心容器。
@Autowired
private ApplicationContext applicationContext;
//進行異步測試
@Override
public List<Courses> asyTest() {
List<Courses> courses = coursesMapper.findAll();
System.out.println(1);
// 打印當前線程的信息
System.out.println("執(zhí)行當前線程的名稱1: " + Thread.currentThread().getName());
// 發(fā)布自定義的課程測試事件
applicationContext.publishEvent(new CoursesTestEvent(this,courses.get(0).getTitle(),courses.get(0).getThumb()));
System.out.println(2);
System.out.println("執(zhí)行當前線程的名稱2: " + Thread.currentThread().getName());
return courses;
}
}
4.代碼執(zhí)行結果(沒有使用異步):

測試達到了監(jiān)聽的效果了,但是都是同一個線程執(zhí)行,按照順序進行執(zhí)行,沒有達到異步的效果。為了增加響應的效率,對監(jiān)聽事件進行異步的執(zhí)行。
Spring Boot的異步任務通常使用以下幾個核心注解:
@EnableAsync:在Spring Boot應用程序的配置類上添加@EnableAsync注解,以啟用異步任務支持。這樣Spring會為異步方法創(chuàng)建一個代理,允許它們在單獨的線程中執(zhí)行。
package com.example.springbootredis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@MapperScan("com.example.springbootredis.mapper")
@EnableAsync //開啟異步任務支持(主要)
public class SpringbootRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedisApplication.class, args);
}
}
@Async:在需要異步執(zhí)行的方法上添加@Async注解。這告訴Spring框架將這個方法的調用包裝在一個新的線程中執(zhí)行。
package com.example.springbootredis.listener;
import com.example.springbootredis.event.CoursesTestEvent;
import com.example.springbootredis.service.CoursesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* 用于測試監(jiān)聽事務,異步執(zhí)行方法
* 課程事件監(jiān)聽器類,用于異步更新課程信息。
*/
@Component
@Slf4j
public class CoursesTestListener {
//根據(jù)實際的需求進行注入
@Autowired
private CoursesService coursesService;
/**
* 異步事件監(jiān)聽方法,用于監(jiān)聽CoursesTestEvent進行更新課程相關信息。
* @param event 觸發(fā)的課程的事件。
*/
// @Async("myTaskExecutor") // 異步執(zhí)行的注解,線程池
@Async() // 異步執(zhí)行的注解
@EventListener // 事件監(jiān)聽器的注解
public void updateLoginInfo(CoursesTestEvent event) {
//檢查是否能夠獲取到CoursesTestEvent
System.out.println("title:"+event.getTitle());
System.out.println("thumb:"+event.getThumb());
System.out.println(3);
// 打印當前線程的信息
System.out.println("執(zhí)行當前線程的名稱3: " + Thread.currentThread().getName());
}
}
再進行測試(異步):

這樣就達到異步的效果了,對監(jiān)聽事件進行異步執(zhí)行。如果想直接進行測試,下面是gitee地址:創(chuàng)建一個數(shù)據(jù)庫將courses.sql文件進行執(zhí)行,啟動即可測試:https://gitee.com/sophisticatedxin/springboot-asy-demo.git
到此這篇關于SpringBoot實現(xiàn)事件監(jiān)聽(異步執(zhí)行)的示例代碼的文章就介紹到這了,更多相關SpringBoot 事件監(jiān)聽內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- springboot 事件監(jiān)聽的實現(xiàn)方法
- SpringBoot Application事件監(jiān)聽的實現(xiàn)方案
- springboot+redis過期事件監(jiān)聽實現(xiàn)過程解析
- SpringBoot加載應用事件監(jiān)聽器代碼實例
- SpringBoot監(jiān)聽事件和處理事件程序示例詳解
- SpringBoot利用切面注解及反射實現(xiàn)事件監(jiān)聽功能
- SpringBoot ApplicationListener事件監(jiān)聽接口使用問題探究
- SpringBoot中的ApplicationListener事件監(jiān)聽器使用詳解
- Springboot事件監(jiān)聽與@Async注解詳解
- Java?Springboot異步執(zhí)行事件監(jiān)聽和處理實例
相關文章
Java多條件判斷場景中規(guī)則執(zhí)行器的設計
近日在公司領到一個小需求,需要對之前已有的試用用戶申請規(guī)則進行拓展。本文去掉if 判斷,試試用一個規(guī)則執(zhí)行器來替代它,感興趣的可以了解一下2021-06-06
Java面試題沖刺第二十八天--數(shù)據(jù)庫(5)
這篇文章主要為大家分享了最有價值的三道關于數(shù)據(jù)庫的面試題,涵蓋內容全面,包括數(shù)據(jù)結構和算法相關的題目、經(jīng)典面試編程題等,感興趣的小伙伴們可以參考一下2021-09-09
java使用Hex編碼解碼實現(xiàn)Aes加密解密功能示例
這篇文章主要介紹了java使用Hex編碼解碼實現(xiàn)Aes加密解密功能,結合完整實例形式分析了Aes加密解密功能的定義與使用方法,需要的朋友可以參考下2017-01-01
使用IDEA搭建SSM框架的詳細教程(spring + springMVC +MyBatis)
這篇文章主要介紹了使用IDEA搭建SSM框架的詳細教程 spring + springMVC +MyBatis,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
Spring Bean實例的創(chuàng)建及構造器的挑選
這篇文章主要介紹了Spring Bean實例的創(chuàng)建及構造器的挑選,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04
解決SpringBoot配置文件application.yml遇到的坑
這篇文章主要介紹了解決SpringBoot配置文件application.yml遇到的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02

