SpringBoot基础

SpringBoot简介

Spring Boot是一个用于创建独立、生产级别的Spring应用程序的框架。它简化了传统的Spring应用开发流程,提供了一种快速、方便的方式来配置和构建Spring应用。SpringBoot的主要特点如下

  • 简化开发:Spring Boot提供了很多开箱即用的特性和功能,例如,自动注册Servlet、Filter和Listener,简化数据库访问(如JPA、MyBatis等)、缓存管理、安全认证等常用功能。
  • 简化配置:Spring Boot通过自动配置(Auto-configuration)功能,根据应用的类路径和依赖来自动推断和配置Spring应用所需的各种组件。开发者只需要进行少量的配置即可,减少了繁琐的XML配置,并提高了开发效率。
  • 注解驱动:Spring Boot采用注解驱动的开发方式,简化了开发者的编码工作,提高了开发效率。
  • 内嵌服务器:Spring Boot内嵌了常用的Web服务器(如Tomcat、Jetty等),无需手动配置和安装,可以直接运行Spring Boot应用程序。
  • 自动依赖管理:Spring Boot会根据项目的依赖关系自动管理和协调相关的库和版本,避免了版本冲突和依赖问题。
  • Actuator监控功能:Spring Boot提供了Actuator模块,可以实时监控和管理Spring Boot应用程序的运行状态、健康状况、性能指标等。

内嵌服务器的更换

常见的内嵌服务器

在 Spring Boot 中,提供了多种内嵌服务器可供选择,常见的内嵌服务器有 Tomcat、Jetty 和 Undertow。默认情况下,Spring Boot 使用 Tomcat 作为内嵌服务器

内置的服务器简介
TomcatApache出品,最常用的内嵌服务器之一,稳定且经过长期验证,适用于传统的 Java Web 应用程序。
Jetty轻量级、高性能的内嵌服务器,更适合现代、高并发的 Web 应用程序开发,负载性能远不及tomcat
Undertow非阻塞的内嵌服务器,具有卓越的性能,适用于需要处理大量并发请求的场景,负载性能勉强跑赢Tomcat

更换为 Jetty

因为Tomcat是默认加载的,更换服务器前提是把Tomcat排除掉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- exclusions标签:依赖排除,排除Tomcat -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- 添加 Jetty 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
</dependencies>

更换为 Undertow

因为Tomcat是默认加载的,更换服务器前提是把Tomcat排除掉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- exclusions标签:依赖排除,排除Tomcat -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- 添加 Undertow 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
</dependencies>

程序的打包与运行

程序的打包

在 Spring Boot 中,通常使用 Maven 进行项目的打包和构建

步骤一:在项目的根目录下的 pom.xml 文件中添加以下插件配置

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

步骤二:在命令行或终端中进入项目的根目录,并执行以下命令进行打包,打包生成的 JAR 文件将存储在 target 目录下

1
mvn package

程序的运行

使用以下命令在命令行或终端中运行 Spring Boot 应用程序

1
java -jar <jar文件名>.jar

入门案例

添加父类依赖

在项目的pom.xml文件中,利用Maven的<parent>标签继承Spring Boot的父类依赖,这个依赖会引入许多常用的Spring Boot依赖和配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<project>
<!-- 继承Spring Boot的父类依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
</parent>

<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>1.0.0</version>

<!-- 其他配置和依赖项 -->

</project>

添加场景依赖

根据实际需要,在pom.xml文件中添加相应的场景依赖。以开发Web程序为例,可以添加spring-boot-starter-web依赖,这样会引入Spring Web相关的依赖,用于开发基于HTTP协议的Web应用程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<project>
<!-- 继承Spring Boot的父类依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
</parent>

<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>1.0.0</version>

<dependencies>
<!-- Spring Web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 其他依赖 -->
</dependencies>

</project>

创建启动程序

创建一个Java类,作为Spring Boot应用程序的入口。该类需要使用@SpringBootApplication注解进行标记,并包含一个main方法用于启动应用程序。这个类使用了@SpringBootApplication注解,它是一个复合注解,包括了@Configuration@EnableAutoConfiguration@ComponentScan等注解,简化了配置的编写。

1
2
3
4
5
6
7
8
@SpringBootApplication
public class MyApplication {

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

}

创建配置文件

src/main/resources目录下创建一个application.properties文件,用于配置应用程序的属性。可以根据需要添加相关配置项。

1
2
# 指定服务器的端口号为8080
server.port = 8080

创建控制器类

创建一个控制器类,用于处理HTTP请求和返回响应。可以使用@RestController注解标记该类,并实现相应的请求处理方法。

1
2
3
4
5
6
7
8
9
@RestController
public class MyController {

@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}

}

SpringBoot配置文件

配置文件名称

Spring Boot有两种常见的配置文件:Application配置文件和Bootstrap配置文件。

Application 配置文件

  • Application配置文件是用于配置应用程序的核心配置信息。
  • Application配置文件通常用于配置应用程序的各种属性和设置,如数据库连接、日志级别、服务端口等。
  • Application 配置文件可位于项目的根目录下config/目录src/main/resources/目录src/main/resources/config/目录

Bootstrap 配置文件

  • Bootstrap配置文件用于在应用程序启动之前进行配置。
  • Bootstrap配置文件主要用于配置Spring Cloud和外部配置服务器等特性。
  • Bootstrap 配置文件可位于项目的根目录下config/目录src/main/resources/目录src/main/resources/config/目录

配置文件格式

Spring Boot支持多种类型的配置文件格式,包括属性文件(.properties)、YAML文件(.yml或.yaml)等格,可以根据项目需求选择最合适的配置文件格式。

属性文件(.properties)

属性文件是一种基于键值对的配置文件格式,每行包含一个属性的键和值,使用等号(=)或冒号(:)作为分隔符。属性文件的扩展名为.properties

1
2
3
4
5
6
7
8
# 设置应用程序的端口号
server.port=8080
# 连接数据库的URL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
# 数据库用户名
spring.datasource.username=root
# 数据库密码
spring.datasource.password=password

YAML文件(.yml或.yaml)

YAML是一种可读性很高的数据序列化格式。它使用缩进和层次结构来表示数据,并提供了更简洁的语法。YAML文件可以通过使用扩展名.yml或.yaml来标识。

1
2
3
4
5
6
7
server:
port: 8080 # 设置应用程序的端口号
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb # 连接数据库的URL
username: root # 数据库用户名
password: password # 数据库用户名

读取配置文件

使用@Value注解读取配置文件

在Spring Boot中,可以通过@Value注解读取配置文件。例如有如下的配置文件

1
2
3
4
5
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb # 连接数据库的URL
username: root # 数据库用户名
password: password # 数据库用户名

可以使用@Value注解将这些值注入到Spring管理的Bean中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@RestController
public class MyController {

@Value("${spring.datasource.url}")
private String dbUrl;

@Value("${spring.datasource.username}")
private String dbUsername;

@Value("${spring.datasource.password}")
private String dbPassword;

@GetMapping("/")
public void test(){
System.out.println("dbUrl: " + dbUrl);
System.out.println("dbUsername: " + dbUsername);
System.out.println("dbPassword: " + dbPassword);
}

}

使用@ConfigurationProperties注解读取配置文件

@ConfigurationProperties注解用于将配置文件中的键值对映射到一个Java类上。例如有如下的配置文件

1
2
3
4
5
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb # 连接数据库的URL
username: root # 数据库用户名
password: password # 数据库用户名

创建一个Java类并提供Getter、Setter方法,使用@Component注解将DataSourceConfig类注入到Spring容器中,在类上添加@ConfigurationProperties(prefix = "spring.datasource")注解,配置文件中以spring.datasource前缀开头的属性值将会映射到DataSourceConfig类的对应字段上。

1
2
3
4
5
6
7
8
9
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceConfig {
private String url;
private String username;
private String password;
}

在其他组件(比如控制器、服务等)中通过@Autowired注解将DataSourceConfig类注入进来,并使用其中的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
public class MyController {

@Autowired
private DataSourceConfig dataSourceConfig;

@GetMapping("/")
public void test(){
System.out.println(dataSourceConfig.getUrl());
System.out.println(dataSourceConfig.getUsername());
System.out.println(dataSourceConfig.getPassword());
}

}

使用@PropertySource注解读取配置文件

@PropertySource注解是Spring Framework中的一个注解,它用于指定外部属性文件的位置,并将其加载到Spring应用程序的环境中。例如有如下的配置文件

1
2
3
4
5
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb # 连接数据库的URL
username: root # 数据库用户名
password: password # 数据库用户名

创建一个Java类并提供Getter、Setter方法,使用@Component注解将DataSourceConfig类注入到Spring容器中,在类上添加@PropertySource(value = "classpath:application.yml",encoding = "UTF-8")注解,指定要加载的配置文件路径

1
2
3
4
5
6
7
8
9
@Getter
@Setter
@Component
@PropertySource(value = "classpath:application.yml",encoding = "UTF-8")
public class DataSourceConfig {
private String url;
private String username;
private String password;
}

在其他组件(比如控制器、服务等)中通过@Autowired注解将DataSourceConfig类注入进来,并使用其中的属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
public class MyController {

@Autowired
private DataSourceConfig dataSourceConfig;

@GetMapping("/")
public void test(){
System.out.println(dataSourceConfig.getUrl());
System.out.println(dataSourceConfig.getUsername());
System.out.println(dataSourceConfig.getPassword());
}

}

使用Environment类读取配置文件

Environment类是Spring Framework中的一个接口,它提供了访问应用程序环境配置属性的方法。通过Environment接口,可以获取和操作与应用程序相关的属性值。例如有如下的配置文件

1
2
3
4
5
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb # 连接数据库的URL
username: root # 数据库用户名
password: password # 数据库用户名

使用Environment类的getProperty方法获取属性值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
public class MyController {

@Autowired
private Environment environment;

@GetMapping("/")
public void test(){
System.out.println(environment.getProperty("spring.datasource.url"));
System.out.println(environment.getProperty("spring.datasource.username"));
System.out.println(environment.getProperty("spring.datasource.password"));
}

}

使用Properties类读取配置文件

Properties 类是 Java 提供的一个用于处理属性文件的类。属性文件通常具有 .properties 扩展名,它以键值对的形式存储配置信息。有些场景不能使用注入的形式去获取配置文件中的参数时,可以使用这种方式。例如有如下的配置文件

1
2
3
4
5
6
# 连接数据库的URL
spring.datasource.url:jdbc:mysql://localhost:3306/mydb
# 数据库用户名
spring.datasource.username:root
# 数据库用户名
spring.datasource.password:password

使用 Properties 对象来读取配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class ConfigReader {
public static void main(String[] args) {
Properties properties = new Properties();

try {
// 使用ClassLoader加载配置文件
InputStream inputStream = ClassLoader.getSystemResourceAsStream("application.properties");
if (inputStream != null) {
// 加载配置文件
properties.load(inputStream);

// 读取配置项
String url = properties.getProperty("spring.datasource.url");
String username = properties.getProperty("spring.datasource.username");
String password = properties.getProperty("spring.datasource.password");

// 输出配置项值
System.out.println("URL: " + url);
System.out.println("Username: " + username);
System.out.println("Password: " + password);
} else {
System.out.println("配置文件未找到");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

多环境配置

多环境配置简介

在实际的项目开发中,一个项目通常会存在多个环境,例如:开发环境、测试环境和生产环境等。

不同环境的配置可能相同,例如开发环境会使用开发数据库,测试环境会使用测试数据库,而生产环境会使用线上的正式数据库

对于这个问题,可以通过Spring Boot的多环境配置来管理不同环境的配置文件,以便在不同的环境中使用不同的配置。

创建不同环境的配置文件

针对不同的环境,可以创建不同的配置文件,通常是application-{环境名}.properties格式或application-{环境名}.yml格式

名称含义
application.yml主配置文件,包含共享的通用配置属性。
application-dev.yml开发环境的配置文件,包含针对开发环境所需的配置属性。
application-test.yml测试环境的配置文件,包含针对测试环境所需的配置属性。
application-prod.yml生产环境的配置文件,包含针对生产环境所需的配置属性。

指定激活的配置文件

方式一:在主配置文件application.yml或application.properties中使用spring.profiles.active属性,设置要激活的配置文件打开application.yml激活指定文件

1
2
3
spring:
profiles:
active: dev # 用来激活不同的环境

方式二:在启动应用程序时使用spring.profiles.active参数来指定指定要激活的环境。

1
java -jar app.jar --spring.profiles.active=dev

配置文件的优先级

从名称角度

如果只考虑文件名,那么:bootstrap > application

从配置文件后缀角度

如果在同一目录下存在多个配置文件,它们的加载顺序是:.properties > .yml > .yaml

从存放位置角度

SpringBoot的配置文件可以放到:项目根目录下、项目根目录中config目录下、项目的src/main/resources目录下、项目src/main/resources/config目录下,他们的读取顺序如下:

  1. 项目根目录中config目录下
  2. 项目根目录下
  3. 项目src/main/resources/config目录下
  4. 项目的src/main/resources目录下

从加载角度

  1. 命令行参数(Command line arguments)
  2. 系统属性(System properties)
  3. 环境变量(Environment variables)
  4. 核心配置文件(bootstrap.propertiesbootstrap.yml
  5. 主配置文件(application.propertiesapplication.yml
  6. 环境配置文件(application-{环境名}.propertiesapplication-{环境名}.yml

SpringBoot常用功能

日志控制

Spring Boot默认使用的是Logback作为日志框架,Logback 是一个功能强大且灵活的日志框架,它是 Log4j 框架的后续版本

默认输出格式

配置输出格式

可以通过修改配置文件来设置日志输出格式

  • %d{yyyy-MM-dd HH:mm:ss.SSS}:输出日期和时间,格式为yyyy-MM-dd HH:mm:ss.SSS
  • [%thread]:输出线程名。
  • %-5level:输出日志级别,占用5个字符的宽度。
  • %logger{36}:输出日志所属类的名称,最多显示36个字符。
  • %msg%n:输出日志消息,并换行。
1
2
3
logging:
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"

配置日志级别

可以通过修改配置文件来设置日志级别

  1. TRACE(追踪):最低级别的日志级别,用于跟踪程序的内部细节。TRACE级别的日志通常包含非常详细的信息,比如方法调用、变量值等。这些日志消息对于诊断问题和调试非常有用,但在正常情况下往往不会被输出。
  2. DEBUG(调试):用于调试应用程序的日志级别。DEBUG级别的日志包含有关程序流程、变量状态和其他调试信息的详细内容。这些日志消息可以帮助开发人员分析代码的执行过程和定位潜在问题。在生产环境中,一般不建议将日志级别设置为DEBUG,以避免日志过多对性能造成影响。
  3. INFO(信息):用于提供应用程序运行时的重要信息。INFO级别的日志通常包含关键的业务事件、操作结果等信息,能够告知应用程序的当前状态和进展情况。INFO级别的日志是生产环境中最常用的级别之一,可用于监控应用程序的运行情况。
  4. WARN(警告):用于表示潜在问题或不符合预期的情况,但不会影响应用程序的正常运行。WARN级别的日志通常用于记录可恢复的异常、配置问题、潜在的性能问题等。这些日志消息提醒开发人员或管理员需要注意,并可能需要采取一定的措施来防止潜在问题变成错误。
  5. ERROR(错误):最高级别的日志级别,用于表示严重的错误或故障。ERROR级别的日志通常包含导致应用程序无法正常工作的异常、错误状态等信息。这些日志消息需要引起开发人员或管理员的关注,并及时采取措施来修复问题。
1
2
3
4
5
logging:
level:
root: INFO # 根日志记录器设置为 INFO 级别。所有未匹配到特定日志记录器的日志消息都将使用此级别。
com.example.package1: DEBUG # 将 com.example.package1 的日志记录器设置为 DEBUG 级别。
com.example.package2: WARN # 将 com.example.package2 的日志记录器设置为 WARN 级别。

热加载

使用SpringBoot开发的时候,修改完代码之后,想要查看修改后的效果,需要手动点击重启,才能让修改生效,十分浪费时间,可以使用或热部署(Hot Deployment)热加载(Hot Reload)避免手动重启程序,提高开发效率

热部署简介

  • 热部署是指在运行时部署或升级新的应用程序版本,以确保应用程序的高可用性和持续提供服务。
  • 一些应用服务器(如Tomcat、Jetty等)支持热部署,可以通过在特定目录中放置更新后的文件来实现热部署。
  • 热部署是在服务器运行时重新部署项目,会直接重新加载整个应用,耗时相对较高,一般是在生产环境使用

热加载简介

  • 热加载是指在运行时替换代码或资源,以实现代码修改的即时生效,方便开发和调试
  • 一些工具和框架(如Spring Boot DevTools、JRebel等)支持热加载,可以自动监测更改并将更改的类重新加载到运行的应用程序中。
  • 热加载是在运行时重新加载 class,后台会启动一个线程不断检测你的类是否改变,一般是在开发环境使用

使用spring-boot-devtools实现热加载

spring-boot-devtools 是 Spring Boot 提供的一个开发者工具插件,它可以在开发阶段自动监测代码的修改并重新加载已加载的类,从而实现代码的即时生效。当你在开发过程中修改保存代码时,spring-boot-devtools 会自动检测到修改,并触发应用程序的重新加载,以便立即应用新的更改。

第一步:在pom.xml添加依赖

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

第二步:IntelliJ IDEA配置配置项目自动编译

第三步:按住Ctrl + Shift + alt + / 打开Maintenance,选择Registry

第四步:在新打开的页面中,勾选compiler.automake.allow.when.app.running 复选框

第五步:在配置文件application.yml中配置devtools

1
2
3
4
5
6
spring:
devtools:
restart:
enabled: true # 设置开启热部署
additional-paths: src/main/java # 设置额外的路径,用于监视并重新加载修改过的文件
exclude: WEB-INF/** # 排除文件(不重启项目)

使用springloaded实现热加载

springloaded 是一个用于 Java 应用程序的类热加载器。它可以在应用程序运行时替换类文件,以实现代码的即时生效,从而提供热加载的功能。当你在开发过程中修改保存代码时,springloaded 可以监测到代码的变化并重新加载已修改的类,这样你就无需重启整个应用程序来查看新的更改。

第一步:在pom.xml添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.experimental</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.8.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

第二步:配置Spring的启动配置

第三步:在VM options里面输入 -javaagent: "jar包的位置" -noverify

指标监控(Actuator)

Actuator简介

Spring Boot Actuator 是 Spring Boot 提供的一组监控和管理生产环境中应用程序的工具,用于公开应用程序的内部信息,并且可以方便地与其他监控工具集成。它通过暴露一组 RESTful 接口和端点,用于获取应用程序的健康状况、指标信息、环境配置等,这些端点可以通过HTTP 和 JMX 访问或者使用外部监控系统调用,从而实现对应用程序的监控和管理。

Actuator简单使用

步骤一:添加 spring-boot-starter-actuator 依赖

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

步骤二:配置开启所有端点暴露,默认情况下 Actuator 端点只有 /actuator/health/actuator/info 会被暴露,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Actuator 监控配置
management:
server:
port: 8080 # Actuator 端口配置,默认是随机端口,配置后将使用指定的端口号

endpoint: # 控制端点是否对外开放的配置(具体端点的配置)
health: # 端点名称
show-details: always # 显示健康检查中所有指标的详细信息
info: # 端点名称
enabled: true # 打开 info 端点,用于提供有关应用程序的信息
httptrace: # 端点名称
enabled: true # 启用 httptrace 端点,用于跟踪 HTTP 请求和响应信息
metrics: # 端点名称
enabled: true # 启用 metrics 端点,用于收集和暴露应用程序的度量指标数据
loggers: # 端点名称
enabled: true # 启用 loggers 端点,用于配置日志记录器
tracing: # 端点名称
enabled: true # 启用 tracing 端点,用于跟踪请求的分布式追踪数据
beans: # 端点名称
enabled: true # 启用 beans 端点,用于查看应用程序中所有的 Spring Bean
mappings: # 端点名称
enabled: true # 启用 mappings 端点,用于查看应用程序中的 URL 映射关系
env: # 端点名称
enabled: true # 启用 env 端点,用于查看应用程序的环境变量
configprops: # 端点名称
enabled: true # 启用 configprops 端点,用于查看应用程序的配置属性
shutdown: # 端点名称
enabled: true # 打开 shutdown 端点,允许通过 POST 请求关闭应用程序

endpoints: # 控制端点是否对外开放的配置(全部端点的配置)
web: # Web 端点的配置
base-path: /actuator # 修改 Actuator 端点的访问路径,默认是 /actuator
exposure: # 暴露端点的配置
include: "*" # 将所有 Actuator 端点都暴露出来,包括自定义的端点,默认只能访问 health 和 info 端点
jmx: # JMX 端点的配置
exposure: # 暴露端点的配置
include: "*" # 将所有 JMX 端点都暴露出来

enabled-by-default: true # 是否开启默认端点,默认值为 true

metrics: # 度量指标的配置
export: # 数据导出的配置
prometheus: # Prometheus 导出器的配置
enabled: true # 启用 Prometheus 数据导出,将度量指标数据暴露给 Prometheus 监控系统

步骤三:访问http://localhost:8080/actuator查看可被健康检查的指标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
{
"_links": {
"self": { // 当前资源的链接
"href": "http://localhost:8080/actuator",
"templated": false
},
"beans": { // 获取应用程序中所有 bean 的链接
"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": { // 获取应用程序健康状况的链接
"href": "http://localhost:8080/actuator/health",
"templated": false
},
"health-path": { // 根据指定路径获取应用程序健康状况的链接(使用占位符)
"href": "http://localhost:8080/actuator/health/{*path}",
"templated": true
},
"info": { // 获取应用程序信息的链接
"href": "http://localhost:8080/actuator/info",
"templated": false
},
"conditions": { // 获取应用程序条件报告的链接
"href": "http://localhost:8080/actuator/conditions",
"templated": false
},
"configprops": { // 获取应用程序配置属性的链接
"href": "http://localhost:8080/actuator/configprops",
"templated": false
},
"configprops-prefix": { // 根据指定前缀获取应用程序配置属性的链接(使用占位符)
"href": "http://localhost:8080/actuator/configprops/{prefix}",
"templated": true
},
"env": { // 获取应用程序环境变量的链接
"href": "http://localhost:8080/actuator/env",
"templated": false
},
"env-toMatch": { // 根据指定匹配模式获取应用程序环境变量的链接(使用占位符)
"href": "http://localhost:8080/actuator/env/{toMatch}",
"templated": true
},
"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": { // 获取应用程序度量指标的链接
"href": "http://localhost:8080/actuator/metrics",
"templated": false
},
"metrics-requiredMetricName": { // 根据指定度量指标名称获取应用程序度量指标的链接(使用占位符)
"href": "http://localhost:8080/actuator/metrics/{requiredMetricName}",
"templated": true
},
"scheduledtasks": { // 获取应用程序定时任务的链接
"href": "http://localhost:8080/actuator/scheduledtasks",
"templated": false
},
"mappings": { // 获取应用程序请求映射的链接
"href": "http://localhost:8080/actuator/mappings",
"templated": false
}
}
}

步骤四:访问 Actuator 常见内置端点

  • 健康检查:访问 /actuator/health 端点,获取应用程序的健康状况信息。
  • 信息展示:访问 /actuator/info 端点,获取应用程序的自定义信息。
  • 度量指标:访问 /actuator/metrics 端点,获取应用程序的度量指标信息。
  • URL 映射关系:访问 /actuator/mappings 端点,获取应用程序中的所有 URL 映射关系。
  • 环境变量:访问 /actuator/env 端点,获取应用程序的环境变量信息。
  • Bean 信息:访问 /actuator/beans 端点,获取应用程序中所有的 Spring Bean 信息。
  • 日志配置:访问 /actuator/loggers 端点,获取应用程序的日志配置和日志级别。
  • 关闭应用程序:访问 /actuator/shutdown 端点,关闭应用程序(需要配置启用该功能)。

设置端点启停

可以在配置文件中使用enable属性控制端点是否对外开放。其中health端点为默认端点,不能关闭

1
2
3
4
5
6
7
8
9
10
11
# Actuator 监控配置
management:
endpoint: # 控制端点是否对外开放
health: # 端点名称
show-details: always # 显示健康检查中所有指标的详细信息
httptrace: # 端点名称
enabled: true # 启用httptrace端点,用于跟踪HTTP请求和响应信息
metrics: # 端点名称
enabled: true # 启用metrics端点,用于收集和暴露应用程序的度量指标数据
shutdown: # 端点名称
enabled: true # 打开shutdown端点,允许通过POST请求关闭应用程序

自定义监控指标

步骤一:创建自定义监控指标端点 CustomMetricsEndpoint.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
// 声明该类为一个 Actuator 端点,拥有唯一的 ID,即 "custommetrics"。enableByDefault 参数表示该端点默认启用。
@Endpoint(id = "custommetrics", enableByDefault = true)
public class CustomMetricsEndpoint {

// 使用 @ReadOperation 注解表示这是一个读取操作的端点方法
@ReadOperation
public Object getCustomValue() {
HashMap<Object, Object> map = new HashMap<>();
map.put("key", "value");
return map;
}

}

步骤二:配置自定义监控指标的端点暴露路径

1
2
3
4
5
management:
endpoints:
web:
exposure:
include: custommetrics # 将自定义监控指标端点 custommetrics 添加到暴露的端点列表中

步骤三:启动应用程序并访问自定义监控指标

1
GET http://localhost/actuator/custommetrics

获取到的信息

1
2
3
{
"key": "value"
}

可视化监控平台

Spring Boot Admin简介

Spring Boot Admin是一个用于管理和监控Spring Boot应用程序的开源项目,建立在 Actuator 之上,提供了更加友好和强大的可视化监控界面和管理功能,能够将 Actuator 中的信息进行界面化的展示,也可以监控所有 Spring Boot 应用的健康状况,提供实时警报功能。

Spring Boot Admin客户端与服务端

一个 Spring Boot Admin 服务端可以监控多个客户端应用程序

  • 客户端:负责将自己的监控信息发送给服务端(被监控者)
  • 服务端:负责接收和展示客户端发送的信息(监控者)

Spring Boot Admin客户端搭建

步骤一:新建模块,添加spring-boot-admin-starter-client依赖,版本与当前使用的springboot版本保持一致,并将其配置成web工程

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.5.4</version>
</dependency>

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

步骤二:创建application.yml配置文件,设置当前客户端将信息上传到哪个服务器上,并配置开放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
spring:
boot:
admin:
client:
url: http://localhost:8080 # 配置服务端的地址
instance:
name: myClient1 # 配置客户端的名称(可选)
# Actuator 监控配置
management:
endpoint: # 控制端点是否对外开放的配置(具体端点的配置)
health: # 端点名称
show-details: always # 显示健康检查中所有指标的详细信息
endpoints: # 控制端点是否对外开放的配置(全部端点的配置)
web: # Web 端点的配置
exposure: # 暴露端点的配置
include: "*" # 将所有 Actuator 端点都暴露出来,包括自定义的端点,默认只能访问 health 和 info 端点

步骤三:创建启动类

1
2
3
4
5
6
7
8
@SpringBootApplication
public class MyApplication {

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

}

步骤四:启动应用程序

Spring Boot Admin服务端搭建

步骤一:新建模块,添加spring-boot-admin-starter-server依赖,版本与当前使用的springboot版本保持一致,并将其配置成web工程

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.5.4</version>
</dependency>

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

步骤二:在启动类上添加@EnableAdminServer注解,声明当前应用启动后作为SpringBootAdmin的服务器使用

1
2
3
4
5
6
7
8
9
@EnableAdminServer
@SpringBootApplication
public class SpringBootAdminServerApplication {

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

}

步骤三:启动程序,访问 http://localhost:8080/applications查看监控数据和管理界面