有一些业务上需要在spring容器启动和关闭的时候做一些操作,那么可以自定义SmartLifecycle接口的实现类来扩展

比如RocketMq的接入  

 

与@PostConstruct的区别:

@PostConstruct 是加在某个bean里的注解,是该bean实例化好后初始化之前即在initializeBean通过postProcessor(InitDestroyAnnotationBeanPostProcessor)调用

 

SmartLifecycle 和 lifeCyle 是接口,是当Spring容器加载所有bean并完成初始化之后(非懒加载),调用start方法

 

pom.xml配置依赖:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.11.RELEASE</version>
        <relativePath/>
    </parent>

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

  

package com.oriente.proxy;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

/**
 * @Description : SmartLifecycle的实现类,在spring容器初始化完毕和关闭的时候被spring容器回调,完成特定的业务需求
 * RokcetMq will listen for the incoming messages from broker server
 */
@Component
@Slf4j
public class RocketMqLifeCycleLinstener implements SmartLifecycle {

    private boolean isRunning = false;

    /**
     * 根据该方法的返回值决定是否执行start方法。<br/>
     * 返回true时start方法会被自动执行,返回false则不会。
     */
    @Override
    public boolean isAutoStartup() {
        System.out.println("method isAutoStartup 11111111");
        // 默认为false
        return true;
    }

    /**
     * 如果工程中有多个实现接口SmartLifecycle的类,则这些类的start的执行顺序按getPhase方法返回值从小到大执行。<br/>
     * 例如:1比2先执行,-1比0先执行。 stop方法的执行顺序则相反,getPhase返回值较大类的stop方法先被调用,小的后被调用。
     */
    @Override
    public int getPhase() {
        System.out.println("method getPhase  2222222");
        // 默认为0
        return 0;
    }

    /**
     * 1. 只有该方法返回false时,start方法才会被执行。<br/>
     * 2. 只有该方法返回true时,stop(Runnable callback)或stop()方法才会被执行。
     */
    @Override
    public boolean isRunning() {
        System.out.println("method isRunning 3333333");
        System.out.println("method isRunning:" + isRunning);
        // 默认返回false
        return isRunning;
    }

    /**
     * 1. 我们主要在该方法中启动任务或者其他异步服务,比如开启MQ接收消息<br/>
     * 2. 当上下文被刷新(所有对象已被实例化和初始化之后)时,将调用该方法,
     * 默认生命周期处理器将检查每个SmartLifecycle对象的isAutoStartup()方法返回的布尔值。
     * 如果为“true”,则该方法会被调用,而不是等待显式调用自己的start()方法。
     */
    @Override
    public void start() {
        System.out.println("method start 44444444");
        // 执行完其他业务后,可以修改 isRunning = true
//        log.info("Start the mq consumer list.");
//        try {
//            for (DefaultMQPushConsumer consumer : consumerList) {
//                consumer.start();
//            }
//        } catch (Exception e) {
//            log.error("Fail to start the mq consumer", e);
//            throw new RuntimeException(e);
//        }
//        log.info("Successfully started the mq consumer list.");

        isRunning = true;
        isRunning = true;
    }


    /**
     * SmartLifecycle子类的才有的方法,当isRunning方法返回true时,该方法才会被调用。
     */
    @Override
    public void stop(Runnable callback) {
        System.out.println("method stop(Runnable)");

        // 如果你让isRunning返回true,需要执行stop这个方法,那么就不要忘记调用callback.run()。
        // 否则在你程序退出时,Spring的DefaultLifecycleProcessor会认为你这个RocketMqLifeCycleLinstener没有stop完成,程序会一直卡着结束不了,等待一定时间(默认超时时间30秒)后才会自动结束。
        // PS:如果你想修改这个默认超时时间,可以按下面思路做,当然下面代码是springmvc配置文件形式的参考,在SpringBoot中自然不是配置xml来完成,这里只是提供一种思路。
        // <bean id="lifecycleProcessor" class="org.springframework.context.support.DefaultLifecycleProcessor">
        //      <!-- timeout value in milliseconds -->
        //      <property name="timeoutPerShutdownPhase" value="10000"/>
        // </bean>
        callback.run();

//        try {
//            for (DefaultMQPushConsumer consumer : consumerList) {
//                consumer.shutdown();
//            }
//        } catch (Exception e) {
//            log.error("Fail to stop the mq consumer", e);
//            throw new RuntimeException(e);
//        }

        isRunning = false;
    }

    /**
     * 接口Lifecycle的子类的方法,只有非SmartLifecycle的子类才会执行该方法。<br/>
     * 1. 该方法只对直接实现接口Lifecycle的类才起作用,对实现SmartLifecycle接口的类无效。<br/>
     * 2. 方法stop()和方法stop(Runnable callback)的区别只在于,后者是SmartLifecycle子类的专属。
     */
    @Override
    public void stop() {
        System.out.println("method stop()");

        isRunning = false;
    }
}

 

可以借助下面的辅助类,代替上面的println来跟踪完整的堆栈信息:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StackLogUtils {

    private static final Logger logger = LoggerFactory.getLogger(StackLogUtils.class);

    public static void main(String[] args) {
        testPrintStackLogs();
    }

    private static void testPrintStackLogs() {
        printStackLogs();
    }

    public static void printStackLogs(){
        //底层调用的还是Exceptin的getStackTrace
//        StackTraceElement[] st = Thread.currentThread().getStackTrace();
        StackTraceElement[] stackTrace = new Throwable().getStackTrace();

        StringBuffer buffer = new StringBuffer();
        if(stackTrace!=null){
            for (StackTraceElement trace : stackTrace) {
                String s = String.format("%s.%s() -> line:%s", trace.getClassName(), trace.getMethodName(), trace.getLineNumber());
                buffer.append(s);
                buffer.append(System.getProperty("line.separator"));
            }
        }
        logger.info("======堆栈信息start========");
        logger.info(buffer.toString());
        logger.info("======堆栈信息end========");
    }
}