您好,登錄后才能下訂單哦!
本篇內容介紹了“springboot事件監聽器怎么使用”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
下面看一個簡單的案例,
@Configuration public class SelfBusiness { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SelfBusiness.class); context.getBean(MyService.class).doBusiness(); context.close(); } @Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ logger.debug("主線業務"); logger.debug("發送短信"); logger.debug("發送郵件"); } }
運行上面的代碼,觀察效果
結合輸出結果,這這段代碼要實現的邏輯是,在主線業務執行完成后,需要執行發短信,發郵件等操作,這樣寫也沒毛病,但不夠優雅,從后續的業務可擴展性上來講,不夠友好,如果后續主線業務執行完畢,還需再增加一個其他的審計操作,則需要新增代碼邏輯,這就將主線業務和支線邏輯緊密的耦合了起來;
就是說,我們期待的效果是,主線業務根本不關心其他的業務操作,只需要完成自身的邏輯就ok了,這就需要使用到spring提供的事件監聽器功能;
使用事件監聽器改造過程
springboot(spring)的事件監聽器使用主要有兩種方式,通過實現ApplicationListener接口,另一個就是在類上添加 @EventListener 注解來實現,接下來將對這兩種方式逐一說明;
static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } }
可以這么理解,在代碼中,可能有很多種類型的事件,不同的業務對應著不同的事件,對于某個具體的監聽器來說,它只想監聽A這種類型的事件;
@Data static class Params { private String id ; private String name; private String phone; } @Component static class SmsApplicationListener implements ApplicationListener<MyEvent> { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); try { Params params = objectMapper.readValue(source.toString(), Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("執行 sms 發短信業務"); } } @Component static class EmailApplicationListener implements ApplicationListener<MyEvent> { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); logger.debug("執行 email 發郵件業務"); } }
顯然,這里的監聽器要監聽的事件類型,正是上面我們定義的MyEvent ,這樣,當業務被觸發的時候,就可以在onApplicationEvent中拿到傳遞過來的參數,從而執行發短信(發郵件)業務操作了
@Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ Params params = new Params(); params.setId("001"); params.setName("xiaoma"); params.setPhone("133******"); logger.debug("主線業務"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } //publisher.publishEvent(new MyEvent("MyService doBusiness()")); //logger.debug("發送短信"); //logger.debug("發送郵件"); } }
對主線業務來說,這時候就不再需要寫發送短信或郵件邏輯了,只需要一個publisher將事件發布出去即可,如果需要傳遞參數,將參數一起傳遞過去
完整的代碼
@Configuration public class SelfBusiness { private static ObjectMapper objectMapper = new ObjectMapper(); public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SelfBusiness.class); context.getBean(MyService.class).doBusiness(); context.close(); } @Data static class Params { private String id ; private String name; private String phone; } /** * 自定義事件對象 */ static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } } @Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ Params params = new Params(); params.setId("001"); params.setName("xiaoma"); params.setPhone("133******"); logger.debug("主線業務"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } //publisher.publishEvent(new MyEvent("MyService doBusiness()")); //logger.debug("發送短信"); //logger.debug("發送郵件"); } } /** * 監聽事件觸發后要執行的業務 */ @Component static class SmsApplicationListener implements ApplicationListener<MyEvent> { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); try { Params params = objectMapper.readValue(source.toString(), Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("執行 sms 發短信業務"); } } @Component static class EmailApplicationListener implements ApplicationListener<MyEvent> { private static final Logger logger = LoggerFactory.getLogger(SmsApplicationListener.class); @Override public void onApplicationEvent(MyEvent myEvent) { Object source = myEvent.getSource(); logger.debug("執行 email 發郵件業務"); } } }
再次運行上面的代碼,觀察效果,可以看到,仍然能滿足預期的效果
這種方式不再需要實現ApplicationListener 接口,而是直接在監聽類的方法上面添加 @EventListener注解即可,相對要簡化了一些,下面直接貼出完整的代碼
package com.congge.config; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Configuration public class SelfBusiness2 { private static ObjectMapper objectMapper = new ObjectMapper(); public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SelfBusiness2.class); context.getBean(MyService.class).doBusiness(); context.close(); } @Data static class Params { private String id ; private String name; private String phone; } /** * 自定義事件對象 */ static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } } @Component static class MyService { private static final Logger logger = LoggerFactory.getLogger(MyService.class); @Autowired private ApplicationEventPublisher publisher; public void doBusiness (){ Params params = new Params(); params.setId("001"); params.setName("xiaoma"); params.setPhone("133******"); logger.debug("主線業務"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } } } @Component static class SmsListenerService { private static final Logger logger = LoggerFactory.getLogger(SmsListenerService.class); @EventListener public void smsListener(MyEvent myEvent){ Object source = myEvent.getSource(); try { SelfBusiness2.Params params = objectMapper.readValue(source.toString(), SelfBusiness2.Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("執行 sms 發短信業務"); } } @Component static class EmailListenerService { private static final Logger logger = LoggerFactory.getLogger(EmailListenerService.class); @EventListener public void emailListener(MyEvent myEvent){ Object source = myEvent.getSource(); try { SelfBusiness2.Params params = objectMapper.readValue(source.toString(), SelfBusiness2.Params.class); logger.debug("userId : {}",params.getId()); } catch (JsonProcessingException e) { e.printStackTrace(); } logger.debug("執行 email 發郵件業務"); } } }
運行上面的代碼,觀察效果,同樣可以達到預期的效果
更進一步來說,為了提升主線業務的邏輯執行效率,我們希望發布事件的業務邏輯異步執行,這個該如何做呢?
翻閱源碼可以知道,ApplicationEventPublisher 默認發布事件時候采用單線程同步發送,如果需要使用異步,需要自定義 ThreadPoolTaskExecutor ,以及SimpleApplicationEventMulticaster ,因此我們只需要覆蓋一下這兩個組件的bean即可,在上面的業務類中將下面的這兩個bean添加進去;
@Bean public ThreadPoolTaskExecutor executor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); return executor; } @Bean public SimpleApplicationEventMulticaster applicationEventMulticaster(ThreadPoolTaskExecutor executor) { SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster(); eventMulticaster.setTaskExecutor(executor); return eventMulticaster; }
這時候再次運行代碼,反復運行多次,就可以看到效果
對比下上面單線程效果
“springboot事件監聽器怎么使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。