架構(gòu)實戰(zhàn)篇(十五):Spring Boot 解耦之事件驅(qū)動

通過使用spring 事件來解決業(yè)務(wù)代碼的耦合

下面通過一個下單的業(yè)務(wù)代碼,拆解為使用事件驅(qū)動的方式開發(fā)

原始的業(yè)務(wù)代碼

package com.itunion.example.service;

import com.itunion.example.domain.Order;
import com.itunion.example.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EmailServiceImpl emailService;

    // 下單
    @Transactional
    public void placeOrder(Order order) {
        // 保存訂單
        orderMapper.save(order);

        // 發(fā)送郵件通知
        emailService.sendEmail(order);
    }
}

這里有個下單接口,首先保存訂單到數(shù)據(jù)庫,然后發(fā)送郵件通知給客戶

思考:如果某一段時間郵件服務(wù)器掛了,那是不是就下不了單了?
如果后續(xù)業(yè)務(wù)變化需要在下單之后增加其他邏輯,是不是需要修改代碼

為了不影響下單我們需要把發(fā)送郵件解耦出來

引入事件發(fā)布對象

package com.itunion.example.service;

import com.itunion.example.domain.Order;
import com.itunion.example.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ApplicationEventPublisher publisher;

    // 下單
    @Transactional
    public void placeOrder(Order order) {
        // 保存訂單
        orderMapper.save(order);

        // 發(fā)布下單事件
        publisher.publishEvent(order);
    }
}

刪除了郵件的依賴和發(fā)送郵件的方法
這里我們引入了 ApplicationEventPublisher 對象,用來發(fā)布下單事件

發(fā)布總要有接收處理事件的地方

接收并處理事件

package com.itunion.example.service;

import com.itunion.example.domain.Order;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl {

    public void sendEmail(Order order) {
        System.out.println("發(fā)送郵件到: " + order.getUserName().toLowerCase());
    }

    @EventListener
    public void placeOrderNotice(Order order) {
        sendEmail(order);
    }

}

sendEmail 是原本的發(fā)送郵件方法,增加一個 placeOrderNotice 方法,并加上@EventListener 注解,這樣只要是Order 類型的消息都會到這個方法里來,然后調(diào)用原本的發(fā)送郵件方法

運行

package com.itunion.example;

import com.itunion.example.domain.Order;
import com.itunion.example.service.OrderServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootEventApplicationTests {

    @Autowired
    private OrderServiceImpl orderService;

    @Test
    public void placeOrder() {
        Order order = new Order();
        order.setUserName("張三");
        order.setGoodsName("iphone X");
        orderService.placeOrder(order);
    }

}

編寫一個單元測試運行一下


正常業(yè)務(wù)都執(zhí)行了

模擬異常

    @Test
    public void placeOrder() {
        Order order = new Order();
        order.setUserName(null);
        order.setGoodsName("iphone X");
        orderService.placeOrder(order);
    }

單元測試的用戶名設(shè)置為空,讓郵件輸出調(diào)用toLowerCase方法是報錯

郵件報錯,訂單事務(wù)回滾了!這不是我們期望的結(jié)果呀

那能不能讓我們的方法異步執(zhí)行呢?答案肯定是可以的

開啟異步執(zhí)行

@EnableAsync
@SpringBootApplication
public class SpringBootEventApplication {

在我們的啟動類上增加一個 @EnableAsync 注解

    @EventListener
    @Async
    public void placeOrderNotice(Order order) {
        sendEmail(order);
    }

在下單事件處理的方法上增加 @Async 異步調(diào)用注解

當(dāng)我們再次執(zhí)行的時候單元測試執(zhí)行通過了,但是控制臺打印了郵件發(fā)送失敗的消息,訂單也入庫了,說明符合我們的逾期結(jié)果

仔細(xì)看日志打印了一個

[cTaskExecutor-1] .a.i.SimpleAsyncUncaughtExceptionHandler 

說明spring 是通過一個默認(rèn)的線程池執(zhí)行了這個發(fā)送郵件的方法,@Async 其實也支持指定你自己配置的線程池的

自定義線程池

 @Bean
    public ThreadPoolTaskExecutor myExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(50);
        return executor;
    }

增加自定義線程池配置 myExecutor ,然后運行查看日志發(fā)現(xiàn)輸出如下內(nèi)容

2018-09-04 13:55:34.597 ERROR 7072 --- [   myExecutor-1]

說明已經(jīng)在使用我們配置的線程池了

也可以增加多個 @EventListener 方法對下單做一連串的后續(xù)操作

當(dāng)有多個下單處理的時候可以使用 @org.springframework.core.annotation.Order 注解來設(shè)置執(zhí)行順序

完整的項目結(jié)構(gòu)

更多精彩內(nèi)容

關(guān)注我們

Git源碼地址:https://github.com/qiaohhgz/spring-boot-event
作者:咖啡

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容