SpringBoot中ApplicationEvent的使用步驟詳解
介紹
ApplicationEvent類似于MQ,是Spring提供的一種發(fā)布訂閱模式的事件處理方式。相對于MQ,其局限在于只能在同一個Spring容器中使用。
使用步驟
封裝消息
將要發(fā)送的內容,封裝成一個bean,這個bean需要繼承ApplicationEvent類。
package com.example.event; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.context.ApplicationEvent; /** * @Description: 封裝消息 * @author: zeal * @date: 2024年04月09日 10:22 */ @Setter @Getter @ToString public class UserLoginEvent extends ApplicationEvent { private Integer userId; private String token; public UserLoginEvent(Object source,Integer userId,String token) { super(source); this.userId=userId; this.token=token; } }
推送消息
推送消息時,注入ApplicationEventPublisher或ApplicationContext均可,調用publishEvent()方法。
package com.example.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Description: 消息推送 * @author: zeal * @date: 2024年04月09日 10:26 */ @RestController @RequestMapping("event") public class UserLoginController { @Autowired private ApplicationContext applicationContext; @RequestMapping("/push") public void pushEvent(){ UserLoginEvent userLoginEvent=new UserLoginEvent(this,001,"zsaf"); applicationContext.publishEvent(userLoginEvent); } }
監(jiān)聽消息
此步驟相當于MQ的消費者,實現(xiàn)ApplicatonListener類,通過泛型來設置消息類型。
package com.example.event; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @Description: 監(jiān)聽消息 * @author: zeal * @date: 2024年04月09日 10:25 */ @Component public class UserLoginEventListener implements ApplicationListener<UserLoginEvent> { @Override public void onApplicationEvent(UserLoginEvent event) { System.out.println("收到消息:"+event.toString()); } }
通過注解實現(xiàn)監(jiān)聽
package com.example.event; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; /** * @Description: 監(jiān)聽消息 * @author: zeal * @date: 2024年04月09日 10:25 */ @Component public class UserLoginEventListener{ @EventListener public void onApplicationEvent(UserLoginEvent event) { System.out.println("收到消息:"+event.toString()); } }
到此這篇關于SpringBoot中ApplicationEvent的用法的文章就介紹到這了,更多相關SpringBoot ApplicationEvent用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Elasticsearch查詢Range Query語法示例
這篇文章主要為大家介紹了Elasticsearch查詢Range Query語法示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04Spring boot如何基于攔截器實現(xiàn)訪問權限限制
這篇文章主要介紹了Spring boot如何基于攔截器實現(xiàn)訪問權限限制,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10springboot實現(xiàn)指定mybatis中mapper文件掃描路徑
這篇文章主要介紹了springboot實現(xiàn)指定mybatis中mapper文件掃描路徑方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06使用@Order控制配置類/AOP/方法/字段的加載順序詳解
這篇文章主要介紹了使用@Order控制配置類/AOP/方法/字段的加載順序詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02