使用SpringBootAdmin监听Nacos注册中心的微服务健康状态
一、搭建SpringBootAdmin项目
1. 引入依赖
此处需要注意SpringBootAdmin的版本,SpringBootAdmin与SpringBoot的版本大致是一一对应的,比如,SpringBoot版本是2.1.x的,SpringBootAdmin的版本也要用2.1.x的,否则可能会启动失败。
<dependencies>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
</dependencies>
2. 配置yaml
spring:
application:
name: pms-monitor
cloud:
nacos:
discovery:
namespace: dev
group: test
server-addr: 127.0.0.1:8848
#开放端点提供服务健康监控
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS
3. 启用注解
@SpringBootApplication
//Nacos服务发现
@EnableDiscoveryClient
//启用Admin监听
@EnableAdminServer
public class PmsMonitorApplication {
public static void main(String[] args) {
SpringApplication.run(PmsMonitorApplication.class, args);
}
}
二、搭建微服务
1. 引入依赖
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
</dependencies>
2. 开放端点提供服务健康监控
spring:
application:
name: pms-service
cloud:
nacos:
discovery:
namespace: dev
group: test
server-addr: 127.0.0.1:8848
#开放端点提供服务健康监控
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS
3. 启用注解
@SpringBootApplication
//Nacos服务发现
@EnableDiscoveryClient
public class PmsMonitorApplication {
public static void main(String[] args) {
SpringApplication.run(PmsMonitorApplication.class, args);
}
}
至此,SpringBootAdmin就能正常采集微服务的健康状态信息了,微服务不需要再做其他配置,SpringBootAdmin会去Nacos注册中心寻找服务进行健康监控。
三、监听失败的情况
正常情况下,SpringBootAdmin采集微服务的健康状态的访问路径是这样子的:
但是,当微服务配置了servlet上下文,即servlet.context-path
时,微服务的访问路径就变成了http://ip:port/${servlet.context-path}/actuator
,故此SpringBootAdmin就无法正常监听微服务的健康了。
所以,需要让SpringBootAdmin的访问路径改变,在Nacos服务发现的配置中添加如下配置即可:
spring:
application:
name: pms-service
cloud:
nacos:
discovery:
namespace: dev
group: test
server-addr: 127.0.0.1:8848
#修改admin健康监控的访问路径
metadata:
management.context-path: /${spring.application.name}/actuator
#配置上下文名称
server:
servlet:
context-path: /${spring.application.name}
#开放端点提供服务健康监控
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: ALWAYS
配置之后,访问路径就会加上项目名,这样就能正常监听了。