Spring Cloud 微服务架构:网关 Zuul、链路追踪 Sleuth 与 Admin 健康检查
本文介绍 Spring Cloud 微服务架构中的三个核心组件。首先讲解网关 Zuul 的概念、配置及负载均衡功能;其次阐述链路追踪的必要性,并演示如何使用 Sleuth 结合 Zipkin 进行分布式跟踪;最后介绍 Spring Cloud Admin 的健康检查机制,包括服务端与客户端配置,以及邮件和钉钉通知的实现。内容涵盖依赖引入、代码示例及关键配置项。

本文介绍 Spring Cloud 微服务架构中的三个核心组件。首先讲解网关 Zuul 的概念、配置及负载均衡功能;其次阐述链路追踪的必要性,并演示如何使用 Sleuth 结合 Zipkin 进行分布式跟踪;最后介绍 Spring Cloud Admin 的健康检查机制,包括服务端与客户端配置,以及邮件和钉钉通知的实现。内容涵盖依赖引入、代码示例及关键配置项。

服务治理,服务注册发现,服务调用,熔断。已经学完。
微服务基本模块已经有了,也可以做微服务了。但完成一个复杂的业务,可能需要多个微服务合作来完成,比如下单,需要用户服务,支付服务,地图服务,订单服务。一般是我们对外服务的窗口,进行服务内外隔离。一般微服务都在内网,不做安全验证。
就好像:很多明星,可以独立开演唱会(独立提供服务)。也可以去春晚(微服务群提供服务)。但一台春晚就不能让 观众一个一个调用了。观众要调用,需要检票啥的,检票就类似于网关,进来之后,界面随便看,不会说你 看个小品,还需要再检票。
微服务没有网关,会有下面的问题:
网关是介于客户端(外部调用方比如 app,h5)和微服务的中间层。
Zuul 是 Netflix 开源的微服务网关,核心是一系列过滤器。这些过滤器可以完成以下功能。
网关和服务的关系:演员和剧场检票人员的关系。
zuul 默认集成了:ribbon 和 hystrix。
新建项目引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
配置文件
eureka.client.service-url.defaultZone=http://euk1.com:7001/eureka/
spring.application.name=zuulserver
server.port=80
启动类
@EnableZuulProxy
测试访问
网关会将服务名转换成具体服务的 ip 和端口,实际进行访问
http://localhost/consumer/alive
启动两个 Consumer
轮询访问上面地址,会看到返回结果中,端口一直轮询在变。说明负载均衡生效了,默认是轮询
consumer.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
调试的时候,看网关请求的地址,以及 映射是否正确。网关请求有误时,可以通过此处排查错误。
配置
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
management.endpoint.health.enabled=true
management.endpoint.routes.enabled=true
zuul.routes.consumer=/xxoo/**
配置前先访问,然后做对比。
zuul.routes.xx.path=/xx/**
zuul.routes.xx.url=http://dyll.com
zuul.routes.xx.path=/xx/**
zuul.routes.xx.service-id=cuid
cuid.ribbon.listOfServers=localhost:82,localhost:83
ribbon.eureka.enabled=false
配置
zuul.ignored-services=user-provider
zuul.prefix=/api/v1
带上前缀请求
zuul.strip-prefix=false
Nginx
网络可靠。
延迟为零。
带宽无限。
网络绝对安全。
网络拓扑不会改变。
必须有一名管理员。
传输成本为零。
网络同质化。(操作系统,协议)
如果能跟踪每个请求,中间请求经过哪些微服务,请求耗时,网络延迟,业务逻辑耗时等。我们就能更好地分析系统瓶颈、解决系统问题。因此链路跟踪很重要。
我们自己思考解决方案:在调用前后加时间戳。捕获异常。
链路追踪目的:解决错综复杂的服务调用中链路的查看。排查慢服务。
市面上链路追踪产品,大部分基于 google 的 Dapper 论文。
zipkin,twitter 开源的。是严格按照谷歌的 Dapper 论文来的。 pinpoint 韩国的 Naver 公司的。 Cat 美团点评的 EagleEye 淘宝的
Sleuth 是 Spring cloud 的分布式跟踪解决方案。
其实数据结构是一颗树,从 root span 开始。
<!-- 引入 sleuth 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
测试点:
[api-driver,1a409c98e7a3cdbf,1a409c98e7a3cdbf,true][服务名称,traceId(一条请求调用链中 唯一 ID),spanID(基本的工作单元,获取数据等),是否让 zipkin 收集和展示此信息] 看下游 [service-sms,1a409c98e7a3cdbf,b3d93470b5cf8434,true] traceId, 是一样的。 服务名必须得写。
上面拍错看日志,很原始。加入利器 zipkin。
zipkin 是 twitter 开源的分布式跟踪系统。
原理收集系统的时序数据,从而追踪微服务架构中系统延时等问题。还有一个友好的界面。
由 4 个部分组成:
Collector、Storage、Restful API、Web UI 组成
采集器,存储器,接口,UI。
原理:
sleuth 收集跟踪信息通过 http 请求发送给 zipkin server,zipkin 将跟踪信息存储,以及提供 RESTful API 接口,zipkin ui 通过调用 api 进行数据展示。
默认内存存储,可以用 mysql,ES 等存储。
操作步骤:
<!-- zipkin -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
spring:
#zipkin
zipkin:
base-url: http://localhost:9411/
#采样比例 1
sleuth:
sampler:
rate: 1
jar 包下载:curl -sSL https://zipkin.io/quickstart.sh | bash -s
java -jar zipkin.jar
# 或者 docker:
docker run -d -p 9411:9411 openzipkin/zipkin
<!-- Admin 服务 -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
</dependency>
<!-- Admin 界面 -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
</dependency>
启动类
package com.example.admin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
@SpringBootApplication
@EnableAdminServer
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}
<!-- Admin 服务 -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
spring.boot.admin.client.url=http://localhost:8080
yml
spring:
application:
name: cloud-admin
security:
user:
name: root
password: root
# 邮件设置
mail:
host: smtp.qq.com
username: 单纯 QQ 号
password: xxxxxxx授权码
properties:
mail:
smpt:
auth: true
starttls:
enable: true
required: true
#收件邮箱
spring.boot.admin.notify.mail.to: 2634982208@qq.com
# 发件邮箱
spring.boot.admin.notify.mail.from: [email protected]
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
package com.example.admin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
@SpringBootApplication
@EnableAdminServer
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
@Bean
public DingDingNotifier dingDingNotifier(InstanceRepository repository) {
return new DingDingNotifier(repository);
}
}
package com.example.admin;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.notify.AbstractStatusChangeNotifier;
import reactor.core.publisher.Mono;
public class DingDingNotifier extends AbstractStatusChangeNotifier {
public DingDingNotifier(InstanceRepository repository) {
super(repository);
}
@Override
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
String serviceName = instance.getRegistration().getName();
String serviceUrl = instance.getRegistration().getServiceUrl();
String status = instance.getStatusInfo().getStatus();
Map<String, Object> details = instance.getStatusInfo().getDetails();
StringBuilder str = new StringBuilder();
str.append("服务预警 : 【" + serviceName + "】");
str.append("【服务地址】" + serviceUrl);
str.append("【状态】" + status);
str.append("【详情】" + JSONObject.toJSONString(details));
return Mono.fromRunnable(() -> {
DingDingMessageUtil.sendTextMessage(str.toString());
});
}
}
package com.example.admin;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
public class DingDingMessageUtil {
public static String access_token = "your_access_token";
public static void sendTextMessage(String msg) {
try {
Message message = new Message();
message.setMsgtype("text");
message.setText(new MessageInfo(msg));
URL url = new URL("https://oapi.dingtalk.com/robot/send?access_token=" + access_token);
// 建立 http 连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
conn.connect();
conn.getOutputStream();
JSONObject.toJSONString(message);
[] data = textMessage.getBytes();
out.write(data);
out.flush();
out.close();
conn.getInputStream();
[] data1 = [in.available()];
in.read(data1);
System.out.println( (data1));
} (Exception e) {
e.printStackTrace();
}
}
}
package com.example.admin;
public class Message {
private String msgtype;
private MessageInfo text;
public String getMsgtype() {
return msgtype;
}
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public MessageInfo getText() {
return text;
}
public void setText(MessageInfo text) {
this.text = text;
}
}
public class MessageInfo {
private String content;
public MessageInfo(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
服务号 模板消息

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online