Spring Cloud :6 . Sleuth+zipkin链路追踪 、Admin健康检查、邮件
Sleuth的使用
最原始的链路追踪,先要在需要监控的服务里添加依赖,这里演示值添加在consumer端和provider端:
<!-- 引入sleuth依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
然后启动项目, 访问url访问即可看到日志输出。
zipkin
zipkin 是基于Sleuth的,zipkin的starter包里面包含了Sleuth
原理 :sleuth收集跟踪信息通过http请求发送给zipkin server,zipkin将跟踪信息存储,以及提供RESTful API接口,zipkin ui通过调用api进行数据展示。默认内存存储,可以用mysql,ES等存储。
依赖包:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
配置
#上报错误信息的URL地址
spring.zipkin.base-url=http://localhost:9411
#采样率
spring.sleuth.sampler.rate=1
启动服务,进行访问,这里测试发生除0异常,会出现提示:
会把错误信息提交到 “http://localhost:9411/api/v2/spans” 地址,但是zipkin Server我们并没有安装,
因此我们需要下载zipkin Server ,它是一个jar包:
直接运行它 -> java -jar zipkin-server-2.21.1-exec.jar
:
然后访问: http://localhost:9411/zipkin/ 进入页面:
重启需要监控的服务,并且请求发生错误,在这个页面就会显示出来:
Spring Cloud Admin健康检查
Server端搭建
Admin分为Server端和Client端。
Server端建立,创建新项目,引入坐标:
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>
把在启动类添加@EnableAdminServer
注解:
@SpringBootApplication
@EnableAdminServer
public class Admin8800Application {
public static void main(String[] args) {
SpringApplication.run(Admin8800Application.class, args);
}
}
配置文件:
server.port=8800
这个时候还没有Client端启动,所以服务列表为空。
Client端搭建
在需要上报Admin的微服务上添加依赖:
<!--actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- admin客户端,集成了actuator-->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.3</version>
</dependency>
配置文件:
#actautor暴露所有接口
management.endpoints.web.exposure.include=*
#显示健康详细
management.endpoint.health.show-details=always
#admin健康检查提交的地址
spring.boot.admin.client.url=http://localhost:8800
然后访问http://localhost:8800 :
总结: admin其实就是把actuator上报的信息整理成为UI页面。
邮件通知
如果某个微服务发生错误,应该如何发送邮件通知呢?
首先在admin项目中添加mail依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置文件:
#邮箱设置
spring.mail.host=smtp.qq.com
spring.mail.username=455386856
#密匙 :需要到邮箱里
spring.mail.password=nyokkxzytcjwbgbh
spring.mail.properties.mail.smpt.auth=true
spring.mail.properties.mail.smpt.starttls.enable=true
spring.mail.properties.mail.smpt.starttls.required=true
# 发件邮箱
spring.boot.admin.notify.mail.from=455386856@qq.com
#收件邮箱
spring.boot.admin.notify.mail.to=8524210@qq.com
配置完成之后重启Admin服务,然后停掉注册到Admin的微服务,邮箱就能收到服务下线的通知了。
这篇文章是本人的个人理解,不保证准确性,如果有错误的地方希望大家留言指正,一起学习共同进步!
如果转载请标明出处。谢谢