1. 程式人生 > 實用技巧 >SpringBoot - 4 監聽 流程 監控 部署

SpringBoot - 4 監聽 流程 監控 部署

SpringBoot - 4 監聽 流程 監控 部署

11-SpringBoot事件監聽

Java中的事件監聽機制定義了以下幾個角色:

①事件:Event,繼承 java.util.EventObject 類的物件

②事件源:Source ,任意物件Object

③監聽器:Listener,實現 java.util.EventListener 介面 的物件

SpringBoot 在專案啟動時,會對幾個監聽器進行回撥,我們可以實現這些監聽器介面,在專案啟動時完成一些操作。

  • ApplicationContextInitializer、

  • SpringApplicationRunListener、

  • CommandLineRunner、

  • ApplicationRunner

    自定義監聽器的啟動時機:MyApplicationRunner和MyCommandLineRunner都是當專案啟動後執行,使用@Component放入容器即可使用

MyApplicationRunner

/**
 * 當專案啟動後執行run方法。
 */
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner...run");
        System.out.println(Arrays.asList(args.getSourceArgs()));
    }
} 

MyCommandLineRunner

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner...run");
        System.out.println(Arrays.asList(args));
    }
}

MyApplicationContextInitializer的使用要在resource資料夾下新增META-INF/spring.factories

org.springframework.context.ApplicationContextInitializer=com.itheima.springbootlistener.listener.MyApplicationContextInitializer
@Component
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer....initialize");
    }
}

MySpringApplicationRunListener的使用要新增構造器

public class MySpringApplicationRunListener implements SpringApplicationRunListener {

    public MySpringApplicationRunListener(SpringApplication application, String[] args) {
    }

    @Override
    public void starting() {
        System.out.println("starting...專案啟動中");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        System.out.println("environmentPrepared...環境物件開始準備");
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("contextPrepared...上下文物件開始準備");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("contextLoaded...上下文物件開始載入");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("started...上下文物件載入完成");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("running...專案啟動完成,開始執行");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("failed...專案啟動失敗");
    }
}

12-SpringBoot流程分析-初始化

  1. 配置啟動引導類(判斷是否有啟動主類)

  2. 判斷是否是Web環境

  3. 獲取初始化類、監聽器類

13-SpringBoot流程分析-run

  1. 啟動計時器

  2. 執行監聽器

  3. 準備環境

  4. 列印banner:可以resource下貼上自定義的banner

  5. 建立context

    refreshContext(context);
    

    執行refreshContext方法後才真正建立Bean

14-SpringBoot監控-actuator基本使用

①匯入依賴座標

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

②訪問http://localhost:8080/acruator

{
    "_links":{
        "self":{
            "href":"http://localhost:8080/actuator",
            "templated":false
        },
        "health":{
            "href":"http://localhost:8080/actuator/health",
            "templated":false
        },
        "health-component-instance":{
            "href":"http://localhost:8080/actuator/health/{component}/{instance}",
            "templated":true
        },
        "health-component":{
            "href":"http://localhost:8080/actuator/health/{component}",
            "templated":true
        },
        "info":{
            "href":"http://localhost:8080/actuator/info",
            "templated":false
        }
    }
}

http://localhost:8080/actuator/info

在application.properties中配置

info.name=lucy
info.age=99

http://localhost:8080/actuator/health

開啟健康檢查詳細資訊

management.endpoint.health.show-details=always
{
    "status":"UP",
    "details":{
        "diskSpace":{
            "status":"UP",
            "details":{
                "total":159579508736,
                "free":13558104064,
                "threshold":10485760
            }
        },
        "redis":{
            "status":"UP",
            "details":{
                "version":"2.4.5"
            }
        }
    }
}

15-SpringBoot監控-actuator開啟所有endpoint

開啟所有endpoint

在application.properties中配置:

management.endpoints.web.exposure.include=*

開啟所有endpoint的返回結果:

{
    "_links":{
        "self":{
            "href":"http://localhost:8080/actuator",
            "templated":false
        },
        "auditevents":{
            "href":"http://localhost:8080/actuator/auditevents",
            "templated":false
        },
        "beans":{
            "href":"http://localhost:8080/actuator/beans",
            "templated":false
        },
        "caches-cache":{
            "href":"http://localhost:8080/actuator/caches/{cache}",
            "templated":true
        },
        "caches":{
            "href":"http://localhost:8080/actuator/caches",
            "templated":false
        },
        "health-component-instance":{
            "href":"http://localhost:8080/actuator/health/{component}/{instance}",
            "templated":true
        },
        "health":{
            "href":"http://localhost:8080/actuator/health",
            "templated":false
        },
        "health-component":{
            "href":"http://localhost:8080/actuator/health/{component}",
            "templated":true
        },
        "conditions":{
            "href":"http://localhost:8080/actuator/conditions",
            "templated":false
        },
        "configprops":{
            "href":"http://localhost:8080/actuator/configprops",
            "templated":false
        },
        "env":{
            "href":"http://localhost:8080/actuator/env",
            "templated":false
        },
        "env-toMatch":{
            "href":"http://localhost:8080/actuator/env/{toMatch}",
            "templated":true
        },
        "info":{
            "href":"http://localhost:8080/actuator/info",
            "templated":false
        },
        "loggers":{
            "href":"http://localhost:8080/actuator/loggers",
            "templated":false
        },
        "loggers-name":{
            "href":"http://localhost:8080/actuator/loggers/{name}",
            "templated":true
        },
        "heapdump":{
            "href":"http://localhost:8080/actuator/heapdump",
            "templated":false
        },
        "threaddump":{
            "href":"http://localhost:8080/actuator/threaddump",
            "templated":false
        },
        "metrics-requiredMetricName":{
            "href":"http://localhost:8080/actuator/metrics/{requiredMetricName}",
            "templated":true
        },
        "metrics":{
            "href":"http://localhost:8080/actuator/metrics",
            "templated":false
        },
        "scheduledtasks":{
            "href":"http://localhost:8080/actuator/scheduledtasks",
            "templated":false
        },
        "httptrace":{
            "href":"http://localhost:8080/actuator/httptrace",
            "templated":false
        },
        "mappings":{
            "href":"http://localhost:8080/actuator/mappings",
            "templated":false
        }
    }
}

16-SpringBoot監控-springboot admin圖形化介面使用

SpringBoot Admin 有兩個角色,客戶端(Client)和服務端(Server)。

以下為建立服務端和客戶端工程步驟:

admin-server:

①建立 admin-server 模組

②匯入依賴座標 admin-starter-server

      <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>

③在引導類上啟用監控功能@EnableAdminServer

@EnableAdminServer
@SpringBootApplication
public class SpringbootAdminServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAdminServerApplication.class, args);
    }

}

admin-client:

①建立 admin-client 模組

②匯入依賴座標 admin-starter-client

  		<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>

③配置相關資訊:server地址等

# 執行admin.server地址
spring.boot.admin.client.url=http://localhost:9000

management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*

④啟動server和client服務,訪問server

17-SpringBoot部署

SpringBoot 專案開發完畢後,支援兩種方式部署到伺服器:

①jar包(官方推薦)

②war包

更改pom檔案中的打包方式為war

修改啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class SpringbootDeployApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDeployApplication.class, args);
    }


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SpringbootDeployApplication.class);
    }
}

指定打包的名稱

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