您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“springboot事件監(jiān)聽(tīng)器怎么使用”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
下面看一個(gè)簡(jiǎn)單的案例,
@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("主線業(yè)務(wù)"); logger.debug("發(fā)送短信"); logger.debug("發(fā)送郵件"); } }
運(yùn)行上面的代碼,觀察效果
結(jié)合輸出結(jié)果,這這段代碼要實(shí)現(xiàn)的邏輯是,在主線業(yè)務(wù)執(zhí)行完成后,需要執(zhí)行發(fā)短信,發(fā)郵件等操作,這樣寫也沒(méi)毛病,但不夠優(yōu)雅,從后續(xù)的業(yè)務(wù)可擴(kuò)展性上來(lái)講,不夠友好,如果后續(xù)主線業(yè)務(wù)執(zhí)行完畢,還需再增加一個(gè)其他的審計(jì)操作,則需要新增代碼邏輯,這就將主線業(yè)務(wù)和支線邏輯緊密的耦合了起來(lái);
就是說(shuō),我們期待的效果是,主線業(yè)務(wù)根本不關(guān)心其他的業(yè)務(wù)操作,只需要完成自身的邏輯就ok了,這就需要使用到spring提供的事件監(jiān)聽(tīng)器功能;
使用事件監(jiān)聽(tīng)器改造過(guò)程
springboot(spring)的事件監(jiān)聽(tīng)器使用主要有兩種方式,通過(guò)實(shí)現(xiàn)ApplicationListener接口,另一個(gè)就是在類上添加 @EventListener 注解來(lái)實(shí)現(xiàn),接下來(lái)將對(duì)這兩種方式逐一說(shuō)明;
static class MyEvent extends ApplicationEvent { public MyEvent(Object source) { super(source); } }
可以這么理解,在代碼中,可能有很多種類型的事件,不同的業(yè)務(wù)對(duì)應(yīng)著不同的事件,對(duì)于某個(gè)具體的監(jiān)聽(tīng)器來(lái)說(shuō),它只想監(jiān)聽(tīng)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("執(zhí)行 sms 發(fā)短信業(yè)務(wù)"); } } @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("執(zhí)行 email 發(fā)郵件業(yè)務(wù)"); } }
顯然,這里的監(jiān)聽(tīng)器要監(jiān)聽(tīng)的事件類型,正是上面我們定義的MyEvent ,這樣,當(dāng)業(yè)務(wù)被觸發(fā)的時(shí)候,就可以在onApplicationEvent中拿到傳遞過(guò)來(lái)的參數(shù),從而執(zhí)行發(fā)短信(發(fā)郵件)業(yè)務(wù)操作了
@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("主線業(yè)務(wù)"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } //publisher.publishEvent(new MyEvent("MyService doBusiness()")); //logger.debug("發(fā)送短信"); //logger.debug("發(fā)送郵件"); } }
對(duì)主線業(yè)務(wù)來(lái)說(shuō),這時(shí)候就不再需要寫發(fā)送短信或郵件邏輯了,只需要一個(gè)publisher將事件發(fā)布出去即可,如果需要傳遞參數(shù),將參數(shù)一起傳遞過(guò)去
完整的代碼
@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; } /** * 自定義事件對(duì)象 */ 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("主線業(yè)務(wù)"); try { publisher.publishEvent(new MyEvent(objectMapper.writeValueAsString(params))); } catch (JsonProcessingException e) { e.printStackTrace(); } //publisher.publishEvent(new MyEvent("MyService doBusiness()")); //logger.debug("發(fā)送短信"); //logger.debug("發(fā)送郵件"); } } /** * 監(jiān)聽(tīng)事件觸發(fā)后要執(zhí)行的業(yè)務(wù) */ @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("執(zhí)行 sms 發(fā)短信業(yè)務(wù)"); } } @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("執(zhí)行 email 發(fā)郵件業(yè)務(wù)"); } } }
再次運(yùn)行上面的代碼,觀察效果,可以看到,仍然能滿足預(yù)期的效果
這種方式不再需要實(shí)現(xiàn)ApplicationListener 接口,而是直接在監(jiān)聽(tīng)類的方法上面添加 @EventListener注解即可,相對(duì)要簡(jiǎn)化了一些,下面直接貼出完整的代碼
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; } /** * 自定義事件對(duì)象 */ 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("主線業(yè)務(wù)"); 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("執(zhí)行 sms 發(fā)短信業(yè)務(wù)"); } } @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("執(zhí)行 email 發(fā)郵件業(yè)務(wù)"); } } }
運(yùn)行上面的代碼,觀察效果,同樣可以達(dá)到預(yù)期的效果
更進(jìn)一步來(lái)說(shuō),為了提升主線業(yè)務(wù)的邏輯執(zhí)行效率,我們希望發(fā)布事件的業(yè)務(wù)邏輯異步執(zhí)行,這個(gè)該如何做呢?
翻閱源碼可以知道,ApplicationEventPublisher 默認(rèn)發(fā)布事件時(shí)候采用單線程同步發(fā)送,如果需要使用異步,需要自定義 ThreadPoolTaskExecutor ,以及SimpleApplicationEventMulticaster ,因此我們只需要覆蓋一下這兩個(gè)組件的bean即可,在上面的業(yè)務(wù)類中將下面的這兩個(gè)bean添加進(jìn)去;
@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; }
這時(shí)候再次運(yùn)行代碼,反復(fù)運(yùn)行多次,就可以看到效果
對(duì)比下上面單線程效果
“springboot事件監(jiān)聽(tīng)器怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。