SpringBoot + Springmvc集成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

注意:上面鏈接的這個文章實現出來的是默認的同步,如果需求要使用異步,那麼參考如下修改:

EventBusAdapter extends EventBus   一定要改爲繼承 AsyncEventBus 類,

然後添加一個構造方法,如下:

public class EventBusAdapter extends AsyncEventBus implements InitializingBean {
 
    private List<EventAbstract> eventBusListener;
 
    // 默認構造方法
	public EventBusAdapter (Executor executor, List<EventAbstract> eventBusListener) {
		super(executor);
		this.eventBusListener = eventBusListener;
	}
 
    @Override
    public void afterPropertiesSet() throws Exception {
        for(EventAbstract eventAbstract : eventBusListener){
            this.register(eventAbstract);
        }
    }

}

spring配置修改:

<!-- spring thread pool executor -->           
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
	<!-- 線程池維護線程的最少數量 -->
	<property name="corePoolSize" value="5" />
	<!-- 允許的空閒時間 -->
	<property name="keepAliveSeconds" value="200" />
	<!-- 線程池維護線程的最大數量 -->
	<property name="maxPoolSize" value="10" />
	<!-- 緩存隊列 -->
	<property name="queueCapacity" value="20" />
	<!-- 對拒絕task的處理策略 -->
	<property name="rejectedExecutionHandler">
		<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
	</property>
</bean>


<!-- EventBusListener 定義 -->
<util:list id="eventBusListener" value-type="com.qyou.EventAbstract">
	<bean class="com.qyou.SendFailMailHandler "/>
	<bean class="com.qyou.SendSuccessSMSHandler "/>
</util:list>

<!-- EventBusAdapter適配器 -->
<bean id="eventBusAdapter" class="com.qyou..EventBusAdapter">
	<constructor-arg name="eventBusListener" ref="eventBusListener"/>
	<constructor-arg name="executor" ref="taskExecutor"/>
</bean>

 

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