【Spring底层原理高级进阶】微服务 Spring Cloud 的注册发现机制:Eureka 的架构设计、服务注册与发现的实现原理,深入掌握 Ribbon 和 Feign 的用法 ️

本文涉及的产品
应用型负载均衡 ALB,每月750个小时 15LCU
网络型负载均衡 NLB,每月750个小时 15LCU
传统型负载均衡 CLB,每月750个小时 15LCU
简介: 【Spring底层原理高级进阶】微服务 Spring Cloud 的注册发现机制:Eureka 的架构设计、服务注册与发现的实现原理,深入掌握 Ribbon 和 Feign 的用法 ️

Spring Cloud的注册发现机制是为了解决微服务架构中服务实例的动态变化和通信的问题。以下是使用Spring Cloud注册发现机制  本文重点讲解其使用方法及原理


Spring Cloud的注册发现机制


Eureka的架构设计


Eureka是Spring Cloud中的一个服务注册和发现组件,它采用了客户端-服务器的架构设计。


Eureka的核心概念


  1. Eureka Server(注册中心):它是服务注册中心,负责接收和存储服务实例的注册信息,并提供服务发现的功能。
  2. Eureka Client(服务实例):它是一个运行在各个服务实例中的客户端,用于将自身的服务注册到Eureka Server,并定期向Eureka Server发送心跳信息以保持注册状态。
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }
}

Eureka Server的角色和功能


  • 注册表:Eureka Server维护一个注册表,用于存储所有已注册的服务实例的信息,包括服务名称、主机地址、端口号等。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
 
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
  • 服务注册:当服务实例启动时,它会向Eureka Server发送注册请求,将自己的信息注册到注册表中。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProviderApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}
 
@RestController
class UserController {
 
    @GetMapping("/users")
    public String getUsers() {
        return "User list";
    }
}
  • 服务续约:服务实例会定期发送心跳信息给Eureka Server,以更新自身的注册状态,并防止被Eureka Server从注册表中注销。
# 心跳间隔(单位:秒)
eureka.instance.lease-renewal-interval-in-seconds=30
# 心跳超时时间(单位:秒)
eureka.instance.lease-expiration-duration-in-seconds=90
  • 服务剔除:如果Eureka Server在一定时间内没有收到服务实例的心跳信息,它会将该服务实例从注册表中剔除。
# 剔除策略启用
eureka.server.eviction.enabled=true
# 剔除策略的时间间隔(单位:秒)
eureka.server.eviction.interval-time-in-ms=60000


eviction.enabled设置为true表示启用剔除策略,eviction.interval-time-in-ms表示剔除策略的时间间隔。如果在该时间间隔内没有收到服务实例的心跳信息,Eureka Server将自动将其从注册表中剔除。


通过以上示例代码和配置,可以实现服务注册、续约和剔除的功能,确保服务实例在Eureka Server上的动态注册和注销。


Eureka Client的角色和功能


  1. 服务注册:服务实例在启动时,会向Eureka Server发送注册请求,将自身的信息注册到Eureka Server的注册表中。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceConsumerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ServiceConsumerApplication.class, args);
    }
}
 
@RestController
class UserController {
 
    private final RestTemplate restTemplate;
 
    public UserController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
 
    @GetMapping("/users")
    public String getUsers() {
        // 通过服务名进行服务发现和调用
        String url = "http://service-provider/users";
        return restTemplate.getForObject(url, String.class);
    }
}

在上述代码中,使用@EnableDiscoveryClient注解启用服务发现功能,并通过RestTemplate发起服务调用。


  1. 服务发现:服务实例通过向Eureka Server发送查询请求,获取其他服务实例的信息,以实现服务之间的通信。

Eureka Server可以以集群的方式部署,实现高可用性和负载均衡。在集群中,各个Eureka Server之间通过复制注册表信息来保持一致性。


  1. 服务调用:服务实例根据获取到的服务实例信息,利用负载均衡等技术选择合适的服务进行调用。


Eureka集群架构的设计和部署


  1. Eureka Server可以以集群的方式部署,实现高可用性和负载均衡。在集群中,各个Eureka Server之间通过复制注册表信息来保持一致性。
  2. 在Eureka集群中,每个Eureka Server既是服务注册中心,又是服务发现的客户端,它们彼此相互注册,以实现相互的服务发现功能。
# Eureka Server 1
eureka.client.serviceUrl.defaultZone=http://server1:8761/eureka/
 
# Eureka Server 2
eureka.client.serviceUrl.defaultZone=http://server2:8762/eureka/


Ribbon的用法


Ribbon是Spring Cloud中的一个客户端负载均衡组件,它与Eureka结合使用可以实现服务间的负载均衡。以下是Ribbon的用法:


  1. Ribbon的作用和特点:


  • Ribbon主要用于在客户端进行负载均衡,将请求分发到多个服务实例上,以提高系统的可用性和性能。
  • Ribbon支持多种负载均衡策略,如轮询、随机、加权等,可以根据需求选择合适的策略。
  • Ribbon与Eureka整合使用时,可以自动从Eureka Server获取可用的服务实例列表。


  1. Ribbon的配置方式:


  • Ribbon可以通过配置文件或编程方式进行配置。
# application.yml
my-service:
  ribbon:
    eureka:
      enabled: true # 启用Eureka集成
    listOfServers: localhost:8081,localhost:8082 # 服务实例列表
    # 可选:设置负载均衡策略
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
  • 配置文件方式:可以在应用的配置文件中设置负载均衡策略和相关属性,如服务名、连接超时、重试次数等。
  • 编程方式:可以通过编写代码来配置Ribbon的负载均衡策略和其他属性,以实现更灵活的配置。


  1. 自定义Ribbon配置:


  • 可以通过自定义配置类来实现Ribbon的个性化配置,如定义特定的负载均衡策略和规则。
  • 自定义配置类需要使用@Configuration注解,并实现IRule接口和其他相关接口,以对Ribbon进行定制化配置。


Feign的用法


Feign是Spring Cloud中的一个声明式的REST客户端,它简化了服务间的HTTP通信,并与Eureka集成实现了服务发现和负载均衡。以下是Feign的用法:


Feign的作用和特点:


  1. Feign用于定义和实现对服务的接口调用,它将接口方法映射到HTTP请求,并通过服务发现和负载均衡来选择合适的服务实例进行调用。
  2. Feign支持声明式的接口定义和注解配置,使得服务间的调用代码更加简洁和易于维护。


声明式REST客户端的使用:


  1. 首先需要定义一个接口,其中声明需要调用的服务方法,并使用@FeignClient注解指定服务名称。
  2. 在接口方法上使用@RequestMapping等注解来配置请求路径、参数等信息。
  3. 使用定义的接口方法进行服务调用时,Feign会自动根据注解配置生成相应的HTTP请求。


Feign的请求参数和路径变量处理:


  1. Feign支持将请求参数通过@RequestParam注解传递,可以配置参数名称、默认值等属性。
  2. 路径变量可以通过@PathVariable注解传递,将参数动态地替换到请求路径中。


Feign的错误处理和重试机制:


  1. Feign提供了对不同HTTP状态码的错误处理机制,可以通过定义ErrorDecoder来处理特定的错误响应。
  2. 可以配置Feign的重试机制,以提高请求的可靠性。可以设置重试次数、重试间隔等属性。


实际用法


  1. 添加依赖:

在Maven项目中,需要添加Spring Cloud Feign的依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>


  1. 创建Feign客户端接口:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
 
@FeignClient(name = "service-provider")
public interface UserServiceClient {
 
    @GetMapping("/users")
    String getUsers();
}

在上述代码中,使用@FeignClient注解指定了服务提供者的名称,这里是service-provider


  1. 创建使用Feign客户端的服务消费者
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@SpringBootApplication
@EnableFeignClients
public class FeignConsumerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(FeignConsumerApplication.class, args);
    }
}
 
@RestController
class UserController {
 
    private final UserServiceClient userServiceClient;
 
    public UserController(UserServiceClient userServiceClient) {
        this.userServiceClient = userServiceClient;
    }
 
    @GetMapping("/users")
    public String getUsers() {
        return userServiceClient.getUsers();
    }
}

在上述代码中,使用@EnableFeignClients注解启用Feign客户端,并通过自动注入的方式使用UserServiceClient进行服务调用。


  1. 配置Feign客户端:

在application.properties或application.yml文件中,配置Feign客户端的相关属性,例如:

# Feign客户端的服务地址
service-provider.ribbon.listOfServers=http://localhost:8080
相关实践学习
小试牛刀,一键部署电商商城
SAE 仅需一键,极速部署一个微服务电商商城,体验 Serverless 带给您的全托管体验,一起来部署吧!
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
相关文章
Spring AOP实现原理
本内容主要介绍了Spring AOP的核心概念、实现机制及代理生成流程。涵盖切面(Aspect)、连接点(Join Point)、通知(Advice)、切点(Pointcut)等关键概念,解析了JDK动态代理与CGLIB代理的原理及对比,并深入探讨了通知执行链路和责任链模式的应用。同时,详细分析了AspectJ注解驱动的AOP解析过程,包括切面识别、切点表达式匹配及通知适配为Advice的机制,帮助理解Spring AOP的工作原理与实现细节。
Spring Cloud Alibaba与Spring Cloud区别和联系?
Spring Cloud Alibaba与Spring Cloud区别和联系?
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
477 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
AI 时代:从 Spring Cloud Alibaba 到 Spring AI Alibaba
本次分享由阿里云智能集团云原生微服务技术负责人李艳林主讲,主题为“AI时代:从Spring Cloud Alibaba到Spring AI Alibaba”。内容涵盖应用架构演进、AI agent框架发展趋势及Spring AI Alibaba的重磅发布。分享介绍了AI原生架构与传统架构的融合,强调了API优先、事件驱动和AI运维的重要性。同时,详细解析了Spring AI Alibaba的三层抽象设计,包括模型支持、工作流智能体编排及生产可用性构建能力,确保安全合规、高效部署与可观测性。最后,结合实际案例展示了如何利用私域数据优化AI应用,提升业务价值。
559 4
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
深入探索Spring Cloud与Spring Boot:构建微服务架构的实践经验
409 5
SpringCloud 微服务nacos和eureka
SpringCloud 微服务nacos和eureka
160 0
【Spring Cloud生态】Spring Cloud Gateway基本配置
【Spring Cloud生态】Spring Cloud Gateway基本配置
174 0
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
117 0
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
123 0
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
66 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问