SpringBoot集成guava

添加guava框架,實現異步處理。

一、添加依賴

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

二、註冊爲組件Bean

import com.google.common.eventbus.AsyncEventBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * web 配置類
 *
 * @author Creator
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * AsyncEventBus註冊
     */
    @Bean
    public AsyncEventBus asyncEventBus() {

        // 創建一個核心3線程,最大10線程的線程池,配置DiscardPolicy策略,拋棄當前任務
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,10,60, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(10),new ThreadPoolExecutor.DiscardPolicy());

        return new AsyncEventBus(threadPoolExecutor);
    }

}

 三、添加事件處理監聽器

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * 異步監聽處理器
 */
@Component
public class AsyncEventListener {

    /**
     * 日誌
     */
    private final static Logger logger = LoggerFactory.getLogger(AsyncEventListener.class);

    @Autowired
    private AsyncEventBus asyncEventBus;

    @Autowired
    private ILoginLogService loginLogService;

    /**
     * 註冊這個監聽器
     */
    @PostConstruct
    public void register(){
        asyncEventBus.register(this);
    }

    /**
     * 具體業務處理(此處比如向庫中添加登錄日誌)
     * sysLoginLogPO: 登錄日誌表對應實體(替換成自己的傳參實體即可)
     */
    @Subscribe
    public void addLoginLog(SysLoginLogPO sysLoginLogPO) {

        logger.info("添加登錄日誌:sysLoginLogPO=" + sysLoginLogPO);

        // 執行具體添加日誌操作
        loginLogService.insert(sysLoginLogPO);
    }

    /**
     * 其他需要異步的業務方法
     */
    @Subscribe
    public void XXX(XXXXPO xxxxpoPO) {

        logger.info("日誌:xxxxpoPO=" + xxxxpoPO);

        // 執行具體添加日誌操作 TODO
    }
}

四、業務層調用

    @Autowired
    private AsyncEventBus asyncEventBus;

    /**
     * 業務處理方法(業務封裝)
     */
    public void doAddLoginLog(){

        SysLoginLogPO sysLoginLogPO = new SysLoginLogPO();

        // 提交異步處理, 會執行AsyncEventListener中的 addLoginLog 方法,根據參數類型匹配
        asyncEventBus.post(sysLoginLogPO);

    }

五、guava同spring集成

可以參考 https://blog.csdn.net/yxp20092010/article/details/46537333

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章