2月14日java假期学习读书笔记

一、学习目标
了解分布式追踪(Spring Cloud Sleuth)的基本概念和作用。
掌握如何在Spring Cloud微服务架构中实现分布式追踪。
了解消息驱动架构(Spring Cloud Stream)的高级特性。
通过实际练习,构建一个支持分布式追踪的消息驱动微服务架构。
理解高可用性和可观察性在微服务架构中的重要性。
二、学习内容
(一)分布式追踪(Spring Cloud Sleuth)

  1. Spring Cloud Sleuth简介
    Spring Cloud Sleuth是一个分布式追踪工具,用于监控和分析微服务架构中的请求路径。
    它可以生成追踪ID和跨度ID,记录每个服务的调用链路。
  2. 集成Spring Cloud Sleuth
    添加依赖:
    xml
org.springframework.cloud spring-cloud-starter-sleuth org.springframework.cloud spring-cloud-starter-zipkin 配置Zipkin服务器: 可以通过Docker快速启动Zipkin服务: bash

docker run -d -p 9411:9411 openzipkin/zipkin
配置应用:
properties

spring.sleuth.sampler.probability=1.0 # 设置采样率
spring.zipkin.base-url=http://localhost:9411
使用Sleuth:
Sleuth会自动为每个请求生成追踪ID,并记录日志。
可以在Zipkin界面中查看追踪信息。
(二)消息驱动架构(Spring Cloud Stream)

  1. Spring Cloud Stream简介
    Spring Cloud Stream是一个用于构建消息驱动微服务的框架,支持多种消息中间件(如RabbitMQ、Kafka)。
    它通过注解和接口简化了消息的发送和接收。
  2. 高级特性
    动态绑定:支持在运行时动态绑定消息通道。
    消息分组:支持将消息分组处理,提高处理效率。
    消息重试:支持在消息处理失败时自动重试。
  3. 配置消息驱动架构
    添加依赖:
    xml
org.springframework.cloud spring-cloud-starter-stream-rabbit 配置消息通道: properties

spring.cloud.stream.bindings.input.destination=myQueue
spring.cloud.stream.bindings.input.group=myGroup
spring.cloud.stream.bindings.output.destination=myQueue
发送消息:
java

@Service
public class MessageSender {
@Autowired
private Source source;

public void sendMessage(String message) {
    source.output().send(MessageBuilder.withPayload(message).build());
}

}

public interface Source {
@Output("output")
MessageChannel output();
}
接收消息:
java

@Service
public class MessageReceiver {
@StreamListener("input")
public void receiveMessage(String message) {
System.out.println("Received message: " + message);
}
}
(三)实际练习:构建一个支持分布式追踪的消息驱动微服务架构

  1. 创建微服务项目
    使用Spring Initializr生成多个微服务项目,如user-service、order-service等。
  2. 集成Spring Cloud Sleuth
    在所有微服务中添加Spring Cloud Sleuth依赖,配置Zipkin服务器。
  3. 集成Spring Cloud Stream
    在order-service中添加Spring Cloud Stream依赖,配置消息通道,发送和接收消息。
  4. 运行和测试
    启动所有微服务,测试消息驱动功能是否正常工作。
    查看Zipkin界面,验证分布式追踪信息是否正确记录。
    三、学习心得
    分布式追踪的重要性
    分布式追踪可以监控和分析微服务架构中的请求路径,帮助快速定位问题。
    Spring Cloud Sleuth结合Zipkin提供了强大的追踪能力,支持可视化界面。
    消息驱动架构的作用
    消息驱动架构可以解耦服务之间的直接调用,提高系统的可扩展性和灵活性。
    Spring Cloud Stream简化了消息的发送和接收,支持多种消息中间件。
    高可用性和可观察性的重要性
    高可用性和可观察性是微服务架构的关键特性,确保系统在故障时能够快速恢复。
    分布式追踪和消息驱动架构是实现高可用性和可观察性的有效手段。
    实践的重要性
    通过实际构建和测试支持分布式追踪的消息驱动微服务架构,我更好地理解了Spring Cloud Sleuth和Spring Cloud Stream的使用方法。
    实践可以帮助快速发现和解决问题,加深对知识点的理解。
posted @ 2025-02-20 00:12  头发少的文不识  阅读(18)  评论(0)    收藏  举报