Spring Cloud常用注解

前言

最近项目使用SpringCloud 比较多,然后通过本篇博客把常用的注解进行汇总分享

@EnableEurekaServer

@EnableEurekaServer 注解的作用是在Spring Boot应用中启用Eureka Server的功能。
主要完成的几件事情是:

  • 注册EurekaServerAutoConfiguration,导入Eureka Server的属性配置
  • 通过注册EurekaServerMarkerConfiguration启用Eureka Server的功能
  • 暴露/eureka/**端点让Eureka客户端注册
  • 加载EurekaServerInitializerConfiguration来处理服务器启动任务
    一个基本的Eureka Server应用大致如下:

    @SpringBootApplication
    @EnableEurekaServer 
    public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
    }

    需要添加Eureka Server的依赖,比如:

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    并配置属性:

    eureka.client.registerWithEureka=false  
    eureka.client.fetchRegistry=false

    以表示这是一个Eureka Server,而不是Eureka Client。
    总之,@EnableEurekaServer 注解在Spring Boot应用中激活了Eureka Server的功能和配置。

    @EnableDiscoveryClient

    @EnableDiscoveryClient 注解的作用是在Spring Boot应用中启用Spring Cloud服务发现功能。
    它主要完成的几件事情是:

  • 注册DiscoveryClientAutoConfiguration,提供DiscoveryClient bean
  • 设置基础设施让应用可以被发现
  • 注册DiscoveryClientConfiguration来处理发现生命周期事件
    一个简单使用发现的服务如下:

    @SpringBootApplication  
    @EnableDiscoveryClient
    public class ServiceDiscoveryApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceDiscoveryApplication.class, args);
    }
    } 

    需要添加发现依赖:

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    以及指向发现服务器的属性:

    eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

    @EnableDiscoveryClient 注解还提供的一些额外的功能是:

  • 注册一个/actuator/info端点,返回发现客户端信息
  • 启动时和运行时续约注册到服务发现
  • 提供一个DiscoveryClient bean,可以注入与服务发现交互
    总之,@EnableDiscoveryClient 注解在Spring Boot应用中通过设置发现客户端和基础设施激活Spring Cloud服务发现的功能。

    @LoadBalanced

    @LoadBalanced 注解为Spring RestTemplate启用负载均衡功能。
    当放在RestTemplate bean上时,它执行以下操作:

  • 为RestTemplate注入一个LoadBalancerInterceptor,它会从ServiceRegistry检索服务,对调用进行包装。
  • LoadBalancerInterceptor使用负载均衡算法从ServiceRegistry中的可用服务实例中选择一个实例。
  • 然后将请求路由到所选的服务实例。
    这允许你按名称调用服务,让负载均衡器确定实际调用哪个服务实例。
    一个示例是:

    @LoadBalanced  
    @Bean
    RestTemplate restTemplate() {
    return new RestTemplate();  
    }
    @Autowired
    RestTemplate restTemplate;  
    public String callService() {
    return restTemplate.getForObject("http://myservice/message", String.class);
    }

    尽管我们调用http://myservice,负载均衡器会选择一个实际的myservice实例来路由请求。
    使用的负载均衡算法取决于你的发现客户端。例如,对于Eureka,默认情况下将是RoundRobin。
    @LoadBalanced注解的一些额外功能是:

  • 缓存服务实例以避免过多调用发现客户端
  • 服务故障时呈指数退避
  • 重试失败的请求
    总之,@LoadBalanced 注解通过配置LoadBalancerInterceptor为RestTemplate启用负载均衡功能。这允许你以客户端不感知的方式调用服务,由负载均衡器确定实际服务实例。

    @EnableCircuitBreaker

    @EnableCircuitBreaker 注解在Spring Boot应用中启用断路器功能。
    它主要完成的几件事情是:

  • 注册CircuitBreakerAutoConfiguration,提供CircuitBreakerFactory bean
  • CircuitBreakerFactory可以创建CircuitBreaker实例来监控服务
  • 注册CircuitBreakerConfiguration,提供CircuitBreaker的默认配置
    一个简单使用断路器的服务如下:

    @SpringBootApplication
    @EnableCircuitBreaker
    public class CircuitBreakerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CircuitBreakerApplication.class, args); 
    }
    } 

    添加断路器依赖:

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

    断路器模式通过将请求切断到服务来提供服务的稳定性和弹性。当目标服务故障或过载时,断路器会临时切断流量,然后缓慢将其恢复。
    @EnableCircuitBreaker为应用程序提供以下功能:

  • 支持使用@HystrixCommand注解的服务方法
  • 处理HystrixThreadPool的初始化
  • 提供/hystrix.stream端点来监控断路器指标
  • 处理断路器生命周期事件
    总之,@EnableCircuitBreaker 注解在Spring Boot应用中通过设置断路器工厂和基础设施启用断路器模式的功能,为应用增加服务的弹性和容错性。

    @HystrixCommand(fallbackMethod=”backMethod”)

    @HystrixCommand 注解表示方法是使用断路器模式保护的。它允许你为方法指定一个回退方法,在调用目标服务失败时调用。
    一个使用 @HystrixCommand 的示例是:

    @HystrixCommand(fallbackMethod = "fallback")
    public String callService() {
    return restTemplate.getForObject("http://service/message");
    }
    public String fallback() {
    return "Fallback message"; 
    }

    这里,如果 callService() 方法由于某种原因失败, fallback() 方法会被调用,返回“Fallback message”。
    @HystrixCommand 注解提供的功能是:

  • 为方法指定一个回退方法,以在执行失败时调用
  • 设置命令名称,用于在Hystrix Dashboard中识别
  • 设置其他断路器选项,如超时时间,并发请求数量等
  • 将方法执行包装在HystrixCommand中,监控其执行并提供回退逻辑
    当 @HystrixCommand 标记的方法:
  • 成功: 方法执行完并返回
  • 失败: 回退方法被调用,返回其结果
  • 拒绝: 回退方法被调用,如果也失败,则触发断路器打开
  • 超时:回退方法被调用
    总之,@HystrixCommand 通过为方法提供回退逻辑和将其执行包装在HystrixCommand中,增加了方法的弹性。这消除了调用方直接依赖目标服务的需求,从而提高了服务间的隔离性。
    一些其他选项,如circuitBreaker.enabled来完全禁用断路器也是可用的。但通常我们使用@HystrixCommand主要是为了利用其回退机制功能。

    @EnableConfigServer

    @EnableConfigServer 注解启用Spring Cloud Config Server功能。
    它主要完成的几件事情是:

  • 注册ConfigServerConfiguration,提供ConfigServerAutoConfiguration中的环境配置
  • 在Spring MVC层注册了一个拦截器,以处理对/config的请求。
  • 暴露出 /{name}/{profile} 、/{name}/{profile}/{label} 等API供客户端获取配置。
  • 从environment中读取git backend配置并设置git仓库信息
    一个基本的Config Server应用如下:

    @SpringBootApplication
    @EnableConfigServer
    public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
    }

    添加依赖如:

    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
    </dependency>

    并在application.properties中配置git仓库信息:

    server.port=8888
    spring.cloud.config.server.git.uri=https://github.com/...

    Config Server主要用于在微服务架构中提供配置服务。它从Git仓库加载配置信息,并使用Spring Cloud配置层抽象向客户端暴露API。
    Clients通过指定name(应用名)、profile(环境)和label(Git branch)来获取对应环境和分支下的配置信息。
    总之,@EnableConfigServer 在Spring Boot应用中激活Spring Cloud Config Server,用于集中管理各微服务的配置信息。

    @EnableZuulProxy

    @EnableZuulProxy 注解启用Spring Cloud Zuul代理功能。
    它主要完成的几件事情是:

  • 注册ZuulProxyAutoConfiguration和ZuulServerAutoConfiguration提供Zuul代理配置
  • 注册ZuulFilterInitializer用于初始化Zuul过滤器链
  • 创建Zuul代理,该代理负责在服务之间路由请求
  • 扫描应用程序上下文寻找ZuulFilter和DelegatingFilterProxy beans,并将其添加到过滤器链中
    一个基本的Zuul代理应用如下:

    @SpringBootApplication
    @EnableZuulProxy
    public class ZuulProxyApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulProxyApplication.class, args);
    }
    }

    添加依赖如:

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

    Zuul代理主要用于在微服务体系架构中提供动态路由,鉴权,压力测试,金丝雀测试等的边缘服务。
    它通过在API网关一层拦截所有请求来实现以上功能。Zuul可以将请求路由到不同后端服务,也可以对请求进行鉴权和过滤。
    Zuul代理根据应用的路由配置来将外部请求映射到内部微服务。路由配置可以通过配置文件或是代码来定义。路由映射支持完全的URL匹配以及通配符。
    总之,@EnableZuulProxy 注解在Spring Boot应用中激活Zuul代理,提供动态路由,过滤,鉴权等边缘服务功能,是微服务架构中重要的一环。

    @SpringCloudApplication

    @SpringCloudApplication 注解是一个组合注解,用于快速启用Spring Cloud的功能。
    它组合了:

  • @EnableDiscoveryClient: 启用服务发现客户端功能
  • @EnableCircuitBreaker: 启用断路器功能
  • @EnableHystrix: 启用Hystrix断路器功能
  • @EnableZuulProxy: 启用Zuul代理功能
  • @EnableFeignClients: 启用Feign声明式HTTP客户端功能
    所以使用 @SpringCloudApplication 注解的应用会自动获得:
  • 服务发现
  • 断路器保护
  • 声明式HTTP客户端
  • Zuul代理(如果需要)
    一个使用 @SpringCloudApplication 的应用示例是:

    @SpringCloudApplication
    public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    }

    这个应用会自动获得:

  • 服务发现客户端(通过Eureka注册)
  • 断路器功能(@HystrixCommand等)
  • Feign HTTP客户端
    相比逐个添加 @Enable* 注解,@SpringCloudApplication 提供了一键启用推荐的Spring Cloud功能组合的便利性,快速构建出一个基于Spring Cloud的应用。
    除了上面提到的四个组件外,如果需要其他的Spring Cloud组件,仍然需要手动添加对应Enable注解,比如:
  • @EnableConfigClient 启用配置客户端
  • @EnableOAuth2Sso 启用OAuth2单点登录
    等等。
    总之,@SpringCloudApplication 注解简化了Spring Cloud应用的启动配置,让开发者可以快速启动一个具有服务发现,断路器,Feign客户端功能的基础云原生应用。

    @ConfigurationProperties

    @ConfigurationProperties 注解用于将配置文件中的属性映射到Java bean中。
    它告诉Spring通过设置前缀来加载对应的属性,并置于bean中。这样我们可以在应用中直接注入使用这些bean,而不需要再去配置文件中查找属性。
    一个使用 @ConfigurationProperties 的示例:

    properties
    server.port=8000
    service.name=MyService
    @ConfigurationProperties(prefix = "service")
    public class ServiceProperties {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    } 
    @Autowired
    ServiceProperties service;
    String name = service.getName(); // MyService

    这里我们通过前缀"service"将配置文件中的service.name属性映射到ServiceProperties bean的name属性中。
    主要功能是:

  • 提供属性的验证,通过@ConfigurationProperties校验属性
  • 提供属性的默认值
  • 简化属性注入,直接注入bean,不需要在配置文件中查找属性
    @ConfigurationProperties 还提供其他功能,如:
  • 指定属性更新的顺序
  • 指定忽略未知的属性
    通常我们会组合使用:
  • @ConfigurationProperties 映射配置文件到bean
  • @Component 注解将bean注册到Spring容器
  • @Autowired 注入使用
    这样我们就可以在应用中直接使用这些配置bean,不需要再去查找配置属性,简化了编程模型。
    总之,@ConfigurationProperties 是一个非常有用的注解,它解耦了配置细节和业务逻辑,通过类型安全的方式将配置映射到Java bean中。这是Spring Boot推荐的处理配置的方式。
Spring Cloud常用注解

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

滚动到顶部