SpringBoot新增監聽器Listener


什么是web監聽器?

  web監聽器是一種Servlet中的特殊的類,它們能幫助開發者監聽web中的特定事件,比如ServletContext,HttpSession,ServletRequest的創建和銷毀;變量的創建、銷毀和修改等。可以在某些動作前后增加處理,實現監控。

監聽器常用的用途

  通常使用Web監聽器做以下的內容:

  統計在線人數,利用HttpSessionLisener

  加載初始化信息:利用ServletContextListener

  統計網站訪問量

  實現訪問監控

1.編寫自定義監聽器BackendConfigListener繼承自GenericApplicationListener

package com.shitou.deposit.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;

import com.alibaba.fastjson.JSONObject;
import com.shitou.deposit.domain.entity.TransactionTradingChannelConfig;
import com.shitou.deposit.domain.impl.TransactionTradingChannelConfigBizFacadeImpl;

/**
 * 應用配置Spring容器監聽器
 * 當容器啟動時,當環境准備好時,加載遠程的配置信息
 * @author zhouky
 * @since 2018年1月11日
 */
public class BackendConfigListener implements GenericApplicationListener {
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger(BackendConfigListener.class);
    
    //指定要監聽的時間
    private static Class<?>[] EVENT_TYPES = { ApplicationEnvironmentPreparedEvent.class,
            ApplicationPreparedEvent.class, ApplicationReadyEvent.class };

    private static Class<?>[] SOURCE_TYPES = { SpringApplication.class, ApplicationContext.class };
    
    private TransactionTradingChannelConfigBizFacadeImpl transactionTradingChannelConfigBizFacadeImpl = null;

    /**
     * 程序啟動時加載應用遠程配置
     * 
     * @param applicationEvent
     */
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ApplicationReadyEvent) {
            //獲取ApplicationReadyEvent中applicationContext
            ConfigurableApplicationContext applicationContext = ((ApplicationReadyEvent) applicationEvent).getApplicationContext();
            //applicationContext獲取Bean
            transactionTradingChannelConfigBizFacadeImpl = (TransactionTradingChannelConfigBizFacadeImpl) applicationContext.getBean("transactionTradingChannelConfigBizFacadeImpl");
            TransactionTradingChannelConfig transactionTradingChannelConfig = transactionTradingChannelConfigBizFacadeImpl.selectByPrimaryKey(1);
            logger.info(JSONObject.toJSONString(transactionTradingChannelConfig));
            logger.info("-------------------- ApplicationReadyEvent ----------------------");
        }
    }

    @Override
    public int getOrder() {
        // 設置加載優先級,在日志之前加載
        return LoggingApplicationListener.DEFAULT_ORDER - 1;
    }

    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        return isAssignableFrom(resolvableType.getRawClass(), EVENT_TYPES);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return isAssignableFrom(sourceType, SOURCE_TYPES);
    }

    private boolean isAssignableFrom(Class<?> type, Class<?>... supportedTypes) {
        if (type != null) {
            for (Class<?> supportedType : supportedTypes) {
                if (supportedType.isAssignableFrom(type)) {
                    return true;
                }
            }
        }
        return false;
    }
}

2.Application啟動類添加自定義監聽器

package com.shitou;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.properties.ConfigurationProperties;

import com.shitou.common.utilities.ShutDownBlockHook;
import com.shitou.common.utilities.ShutDownHookLevel;
import com.shitou.config.ConfigApplicationListener;
import com.shitou.deposit.listener.BackendConfigListener;

@ConfigurationProperties("server")
@SpringBootApplication
public class Application implements EmbeddedServletContainerCustomizer {
    private static Logger logger = LoggerFactory.getLogger(Application.class);

    private int port = 8080;

    public void setPort(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        SpringApplication app = new SpringApplication(Application.class);
        // 加載remote config
        app.addListeners(new ConfigApplicationListener());
        // 加載database config
        app.addListeners(new BackendConfigListener());
        app.run(args);
        ShutDownBlockHook.registerHook(new ShutDownBlockHook.ShutDownRunning(){
            
            @Override
            public void run() {
                logger.info("Application ShutDownBlockHook .............");
            }
        }, ShutDownHookLevel.LoggingHookLevel);
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {

        container.setPort(this.port);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM