1. 描述
一个springboot项目使用actuator, 对spring-boot应用进行监控(监测和控制)的 demo示例。
环境:
IDE(idea):2021.3
JDK:1.8
maven:3.8.4
spring boot:2.5.6
2. 结果
- 页面登陆,并访问监控信息
3. demo
3.0 项目结构
3.1 pom.xml
- 引入 actuator jar包
<dependencies>
<!--提供全栈的 web 开发特性,包括 Spring MVC 依赖和 Tomcat 容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--提供对spring-boot应用的监控(监测和控制)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 提供通用单元测试依赖,包括 JUnit, Hamcrest , Mockito-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3.2 SpringBootApplication 注解实现启动类
@SpringBootApplication
public class DemoActuatorApplication {
public static void main(String[] args) {
SpringApplication.run(DemoActuatorApplication.class, args);
System.out.println("----- http://localhost:8880/demo/ -----");
System.out.println("----- http://localhost:8890/sys/actuator -----");
}
}
3.3 application.yml配置
- 端口和应用路径
- 监控端口、路径,监控内容等相关信息
application.yml
server:
port: 8880
servlet:
context-path: /demo
spring:
application:
name: ${project.artifactId}
# 若要访问服务信息,需要配置用户名和密码
security:
user:
name: byrc
password: 123456
management:
# 端点信息接口使用的端口,为了和主系统接口使用的端口进行分离
server:
port: 8890
servlet:
context-path: /sys
# 端点健康情况,默认值"never",设置为"always"可以显示硬盘使用情况和线程情况
endpoint:
health:
show-details: always
# 设置端点暴露的哪些内容,默认["health","info"],设置"*"代表暴露所有可访问的端点
endpoints:
web:
exposure:
include: 'info'
3.4 其他代码
- TestController.java
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping(value = "/hello", name = "返回Hello World")
public String hello(@RequestParam(value = "name", required = false) String name) {
return String.format("Hello %s! ", name == null ? "World" : name);
}
}
4. 资料
官网:https://spring.io/projects/spring-boot/
5. 注
- spirng boot 已在父项目引入(父项目pom.xml配置);
- 部分jar包版本已在父项目管理(如果对应不上,一定、肯定、决定是某些修改,没同步更新文档)。