SpringCloud

一、基本理念

1.1 Microservices

微服务架构是“新常态”。构建小型的、自包含的、随时可以运行的应用程序可以为代码带来极大的灵活性和弹性。Spring Boot 的许多专门构建的特性使得在生产环境中大规模地构建和运行微服务变得非常容易。别忘了,没有 Spring Cloud 放松管理和提高容错能力,任何微服务架构都是不完整的。

1.1.1 What is Microservices

微服务是一种现代的软件开发方法,应用程序代码以可管理的小块形式交付,独立于其他块。

1.1.2 Why Microservices

它们的小规模和相对隔离可以带来许多额外的好处,例如更容易维护、提高生产率、更大的容错性、更好的业务协调等等。

1.2 SpringCloud

Spring Cloud 为开发人员提供了工具,以快速构建分布式系统中的一些常见模式(例如,配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁,领导选举,分布式会话,群集状态)。分布式系统的协调导致样板式样,并且使用Spring Cloud开发人员可以快速站起来实现这些样板的服务和应用程序。它们可以在任何分布式环境中正常工作,包括开发人员自己的笔记本电脑,裸机数据中心以及Cloud Foundry等托管平台。

1.2.1 What is SpringCloud

Spring Cloud 是一个微服务框架,相比 Dubbo 等 RPC 框架, Spring Cloud 提供的全套的分布式系统解决方案。对微服务基础框架 Netflix 的多个开源组件进行了封装,同时又实现了和云端平台以及和 Spring Boot 开发框架的集成。 为微服务架构开发涉及的 配置管理,服务治理,熔断机制,智能路由,微代理,控制总线,一次性 token,全局一致性锁,leader 选举,分布式session,集群状态 管理等操作提供了一种简单的开发方式。为开发者提供了快速构建 分布式系统的工具,开发者可以快速的启动服务或构建应用、同时能够快速和云平台资源进行对接。

1.2.2 Why SpringCloud

  • Distributed/versioned configuration

    分布式/版本化配置

  • Service registration and discovery

    服务注册和发现

  • Routing

    路由

  • Service-to-service calls

    服务间的调用

  • Load balancing

    负载均衡

  • Circuit Breakers

    断路器

  • Global locks

    全局锁

  • Leadership election and cluster state

    领导选举和集群状态

  • Distributed messaging

    分布式消息传递

二、服务注册中心

2.1 Eureka

2.1.1 What is Eureka

官方文档 链接

Eureka is a REST (Representational State Transfer) based service that is primarily used in the AWS cloud for locating services for the purpose of load balancing and failover of middle-tier servers. We call this service, the Eureka Server. Eureka also comes with a Java-based client component,the Eureka Client, which makes interactions with the service much easier. The client also has a built-in load balancer that does basic round-robin load balancing. At Netflix, a much more sophisticated load balancer wraps Eureka to provide weighted load balancing based on several factors like traffic, resource usage, error conditions etc to provide superior resiliency.

人话

是一个服务注册和发现的平台,带有负载均衡的功能,我们只要简单的配置,就能实现服务的注册,并能通过 Eureka 的客户端实时观察到相关信息,有了 Eureka,就可以将多个功能相同的微服务统一服务名,注册进 Eureka,当外界调用时,就可以通过统一的服务名实现负载均衡的调用

心跳

默认每 30 秒向已注册的服务发送一次心跳包,若能收到回复则说明该服务可用,若 90 秒没有收到该服务的心跳包则说明该服务已挂,将此服务移除。

2.1.2 Dependency

server

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

client

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

2.1.3 Use

  • 首先引入 2.1.2 的依赖(服务端引入服务端的,客户端引入客户端的)
  • 其次在 application.yml 进行配置,参考附录 8.1 的属性,下面是常用属性
1
2
3
4
5
6
7
8
eureka:
instance:
hostname: {url}:{port}
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://{url}:{port}/eureka

比如

  • 服务端
1
2
3
4
5
6
7
8
server:
port: 7001
eureka:
client:
register-with-eureka: false # 不注册进 eureka,因为自己就是
fetch-registry: false # 同
service-url:
defaultZone: http://localhost:7001/eureka
  • 客户端
1
2
3
4
5
6
7
8
server:
port: 80
eureka:
client:
register-with-eureka: true # 这个当然就要注册进 eureka 了
fetch-registry: true # 同
service-url:
defaultZone: http://localhost:7001/eureka
  • 在主启动类添加注解 @EnableEurekaServer@EnableEurekaClient
  • 最后访问 Eureka 客户端,url 为 localhost,端口为微服务端口
  • image-20200428235723565

2.2 Zookeeper

2.2.1 What is Zookeeper

官方文档

Spring Cloud Zookeeper provides Apache Zookeeper integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms. With a few simple annotations you can quickly enable and configure the common patterns inside your application and build large distributed systems with Zookeeper. The patterns provided include Service Discovery and Distributed Configuration.

人话

和 Eureka 一样的,都是服务注册中心,只要简单的注解和配置就能实现服务注册和服务发现,不过 Zookeeper 并没有可视化 web 客户端,而是一个类 Linux 操作的控制台作为客户端,而且 Zookeeper 的服务器也是这种形式

2.2.2 Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>

2.2.3 Use

  • 配置好 Zookeeper,然后启动 Zookeeper 服务器

  • 微服务的启动:

    • 引入 2.2.2 的依赖
  • 配置 application.yml

1
2
3
4
spring:
cloud:
zookeeper:
connect-string: localhost:2181
  • 启动微服务

  • 可通过 Zookeeper 客户端查看已注册的服务

2.3 Consul

2.3.1 What is Consul

官方文档 链接

Spring Cloud Consul provides Consul integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms. With a few simple annotations you can quickly enable and configure the common patterns inside your application and build large distributed systems with Hashicorp’s Consul. The patterns provided include Service Discovery, Distributed Configuration and Control Bus.

人话

同 Eureka 和 Zookeeper,不过服务器需下载,有 web 界面客户端

2.3.2 Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>

2.3.3 Use

  • 首先下载 Consul,用 consul.exe agent -dev 命令启动

  • http://localhost:8500/ 访问一下,看有没有启动成功

  • 微服务启动:

    • 首先引入 2.3.2 的依赖

    • 配置 application.yml 文件

1
2
3
4
5
6
7
spring:
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: ${spring.application.name}
  • 启动

三、服务调用

3.1 Ribbon

3.1.1 What is Ribbon

官方文档 链接

Ribbon plays a critical role in supporting inter-process communication in the cloud. The library includes the Netflix client side load balancers and clients for middle tier services.

人话

Ribbon 用于云端微服务之间的通信,包含了 Netflix 的负载均衡器和中间层客户端,而且在前面的 Eureka 里已经使用过 Ribbon 了

3.1.2 Dependency

1
2
3
4
5
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>

3.1.3 Use

  • 引入依赖

  • 配置 RestTemplate 类

1
2
3
4
5
6
7
8
@Configuration
public class TemplateConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
  • 注入 RestTemplate 对象 rt

  • 使用 rt.getForObject() 和 rt.postForObject() 进行服务调用即可,或使用 rt.getObjectForEntity() / rt.postObjectForEntity(),后面两种更为详细,包含状态码等信息。

负载均衡算法

  • RoundRobinRule – 轮询
  • RandomRule – 随机
  • RetryRule – 先轮询,若失败会在指定时间内重试
  • WeightedResponseTimeRule – 响应速度越快的越容易被选中
  • BestAvailableRule – 会先过滤掉因多次访问故障进入熔断状态的微服务,并选择一个并发量最小的服务
  • AvailabilityFilteringRule – 先过滤故障服务,并选择并发较小的
  • ZoneAvoidanceRule – 复合判断 server 所在区域的性能和 server 的可用性的可选择性服务器

负载均衡切换

根据官方文档所说,该配置类不能放在 @ComponentScan 能扫描到的地方,而 @SpringBootApplication 注解自带了 @ComponentScan,所以我们的配置文件不能放在主启动的同一个包或子包下,应如下所示

image-20200501125851117

然后编写配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.cying.ribbon;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRule {
@Bean
public IRule myRule() {
return new 负载均衡算法();
}
}
// 注意,Ribbon 负载均衡是用于客户端,所以该配置类也只需在客户端配置

3.2 OpenFeign

3.2.1 What is OpenFeign

官方文档 链接

This project provides OpenFeign integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms.

人话

在 Ribbon + RestTemplate 的基础上进一步封装,对外只需提供接口即可,更符合 SpringMVC 规范

3.2.2 Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

3.2.3 Use

  • 引入依赖

    • 书写主启动类,在主启动类标注 @EnableFeignClient 注解
  • 书写接口,在接口上标注 @Component 和 @FeignClient(value=””) 注解,value 里是要调用的服务名

  • 接口类的方法上也需要 @GetMapping,@PostMapping 或者 @RequestMapping 注解,路径即要请求的路径。

  • 比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.cying.cloud.service;

import com.cying.cloud.entities.CommonResult;
import com.cying.cloud.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "Consul-Payment") // 这里是要请求的服务
public interface PaymentService {
@GetMapping("/c/get/{id}") // 这里就是要请求的路径
CommonResult<Payment> get(@PathVariable("id") Long id);
}

超时设置

OpenFeign 默认等待一秒,但有些业务可能一秒之内完成不了,顾需要自定义时间

1
2
3
ribbon:
ReadTimeout: ? // 建立连接允许时间
ConnectTimeout: ? // 得到回复允许时间

四、服务断路器

4.1 Hystrix

4.1.1 What is Hystrix

官方文档 链接

In a distributed environment, inevitably some of the many service dependencies will fail. Hystrix is a library that helps you control the interactions between these distributed services by adding latency tolerance and fault tolerance logic. Hystrix does this by isolating points of access between the services, stopping cascading failures across them, and providing fallback options, all of which improve your system’s overall resiliency.

人话

当微服务出现故障或者调用失败时采取一定的措施以保证整个系统的可用性。包括服务限流,服务降级,服务熔断。

  • 服务限流:当一个微服务的访问量突然之间变得很大时采取的措施

  • 服务降级:当服务器忙时,不让客户端一直等待,而是返回一个友好提示

    • 触发条件
      • 程序运行异常时
      • 超时
      • 服务熔断时
      • 线程池/信号量打满时
  • 服务熔断:当达到最大服务访问后,直接拒绝访问,拉闸限电,然后调用服务降级的方法并返回友好提示

    • 触发条件
      • 某个微服务出错,不可用或者响应时间太长
    • 缺省条件
      • 5s 内 20 次调用失败
    • 基本原理
      • 让断路器本身检测基础调用是否再次工作正常。可以通过在适当的时间间隔后再次尝试受保护的调用来实现这种自我的重置行为,并在成功后重置断路器

    image-20200501233446496

    image-20200502000553661

    image-20200502000553661

4.1.2 Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

4.1.3 Use

  • 引入 4.1.2 的依赖

4.1.3.1 fallback

4.1.3.1.1 用于服务端
  • 在主启动类添加 @EnableCircuitBreaker 注解
  • 在需要降级的方法上添加 @HystrixCommand 注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@GetMapping(value = "/hs/get/{id}")
@HystrixCommand(
fallbackMethod = "getEHandler", // 服务降级处理方法
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000") // 限定处理时间,若超过 4 秒则进行服务降级,跳转至处理方法
}
)
public CommonResult<Payment> getE(@PathVariable("id") Long id) {
try {
TimeUnit.SECONDS.sleep(10); // 模拟重量级程序,需处理十秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
return new CommonResult<>(200, Thread.currentThread().getStackTrace().toString(), port, service.getPaymentById(id));
}

//降级处理方法
public CommonResult<Payment> getEHandler(Long id) {
return new CommonResult<>(200, Thread.currentThread().getStackTrace().toString(), "请求超时", new Payment(null, null));
}
4.1.3.1.2 用于客户端
  • 在主启动类添加 @EnableHystrix 注解
  • 在需要降级的方法上添加 @HystrixCommand 注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@GetMapping(value = "/gete/{id}")
@HystrixCommand(
fallbackMethod = "geteHandler", // 服务降级处理方法
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") // 限定处理时间,若超过 1 秒则进行服务降级,跳转至处理方法
}
)
public CommonResult<Payment> gete(@PathVariable("id") Long id) {
return service.getE(id);
}

//降级处理方法
public CommonResult<Payment> geteHandler(Long id) {
return new CommonResult<>(200, Thread.currentThread().getStackTrace().toString(), "这里是客户端降级处理,服务请求已超时", new Payment(null, null));
}

4.1.3.1.3 全局降级方法
  • 在需要降级的类上写上 @DefaultProperties(defaultFallback = “方法名”) 注解
  • 在需要使用全局服务降级的方法上直接写上 @HystrixCommand 注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "myFall")
public class OrderController {

@Resource
private OrderService service;

@HystrixCommand(
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") // 限定处理时间,若超过 1 秒则进行服务降级,跳转至处理方法
}
)
@GetMapping(value = "/geteg/{id}")
public CommonResult<Payment> geteg(@PathVariable("id") Long id) {
return service.getE(id);
}

public CommonResult<Payment> myFall() {
return new CommonResult<>(200, Thread.currentThread().getStackTrace().toString(), "全局降级方法", new Payment());
}

}

4.1.3.1.4 结合 OpenFeign
  • 在 application.yml 配置 feign.hystrix.enabled = true
  • 新建类,实现 OpenFeign 接口,在实现的方法里写降级逻辑
  • 在 OpenFeign 接口的 @FeignClient 注解中添加属性 fallback = 实现类

4.1.3.2 CirecuitBreaker

  • 同样,在需要熔断的方法上添加 @HystrixCommand 注解,并指定 fallbackMethod 为解决方法

  • 添加 commandProperties 属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
commandProperties = {
// 是否开启断路器
@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
// 请求次数
@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
// 时间窗口期
@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
// 错误率
@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
}

/*
* 结合起来的意思就是,当 10 秒钟内,10 次有 60% 的请求出错则开启断路器
*/

4.1.4 Hystrix Dashboard

  • 新建 Module

  • 引入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
  • 创建主启动类并启动

五、服务网关

5.1 Gateway

5.1.1 What is Gateway

官方文档

This project provides a library for building an API Gateway on top of Spring MVC. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.

人话

此 Gateway 不是你第一想到的那个 Gateway,也就是常被称作网关的 Gateway,这里的 Gateway 是 Spring 公司的产品,是网关 Gateway 理念的实现产品。追求极简的配置完成 API 的跳转,基于 webFlux 的非阻塞架构

三大特性

  • Route
  • Predicate
  • Filter

工作流程

image-20200503201603217

5.1.2 Dependency

1
2
3
4
5
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 注意,此处不需引入 web 和 acturator 依赖 -->

5.1.3 Use

5.1.3.1 Route & Predicate

1
2
3
4
5
6
7
8
9
10
11
spring:
cloud:
gateway:
discovery: // 开启微服务动态路由
locator:
enabled: true
routes: // 配置路由
- id: cp1 // 第一条的 id
uri: lb://Consul-Payment // lb:// + 要访问的微服务名
predicates:
- Path=/c/get/** // 断言,当请求路径以 /c/get/开头才允许通过

5.1.3.2 Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter,Ordered {
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String uname = exchange.getRequest().getQueryParams().getFirst("uname"); //获取第一个参数
if(uname == null) {
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); //设置状态码
return exchange.getResponse().setComplete(); //返回
}
return chain.filter(exchange); // 放行
}
public int getOrder() {
return 0; //这个方法是设置优先级的,0 最先执行
}
}

5.1.3.3.CORS

1
2
3
4
5
6
7
8
9
10
11
12
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': //正则表达式
allow-credentials: true //是否允许
allowed-origins: //允许哪些
- "null"
allowed-headers: "*" //允许的请求头
allowed-methods: //允许的请求方法
- GET

六、服务配置

6.1 Config

6.1.1 What is Config

官方文档

Spring Cloud Config provides server and client-side support for externalized configuration in a distributed system. With the Config Server you have a central place to manage external properties for applications across all environments. The concepts on both client and server map identically to the Spring Environment and PropertySource abstractions, so they fit very well with Spring applications, but can be used with any application running in any language. As an application moves through the deployment pipeline from dev to test and into production you can manage the configuration between those environments and be certain that applications have everything they need to run when they migrate. The default implementation of the server storage backend uses git so it easily supports labelled versions of configuration environments, as well as being accessible to a wide range of tooling for managing the content. It is easy to add alternative implementations and plug them in with Spring configuration.

人话

在工作中,我们有很多配置可能是通用的,比如数据库的配置,当数据库做了迁移,那么所有连接都要更改,会造成一定麻烦,所以这里的 config 就是为了管理全局配置而生的插件环境,通过将配置文件存放了 git 上,通过一个 config server 读取到 git 的配置,并通知其他平台更新,达到一处修改,处处生效的结果

6.1.2 Dependency

server

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>

client

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>

6.1.3 Use

  • 引入依赖

  • 配置 application.yml

    • 服务端
1
2
3
4
5
6
7
8
9
spring:
cloud:
config:
server:
git:
uri: git@github.com:CyingK/springcloud-config.git //地址
search-paths:
- springcloud-config //路径
label: master //分支
  • 客户端
1
2
3
4
5
6
7
8
9
spring:
cloud:
config:
label: master // 分支
name: config // 名称
profile: dev // 环境
uri: http://localhost:? // config服务器地址

// 注意,因为要在 application.yml 加载完成之前完成 config 的拉取,所以这些配置都要写在 bootstrap.yml
  • 书写主启动类,服务端要添加 @EnableConfigServer 注解

  • 启动

  • 查看

    • localhost:{port}/{lable}/{application}-{profile}.yml
    • localhost:{port}/{application}-{profile}.yml
    • localhost:{port}/{application}/{profile}[/{lable}]

七、服务总线

7.1 Bus

7.1.1 What is Bus

官方文档

Spring Cloud Bus links nodes of a distributed system with a lightweight message broker. This can then be used to broadcast state changes (e.g. configuration changes) or other management instructions. AMQP and Kafka broker implementations are included with the project. Alternatively, any Spring Cloud Stream binder found on the classpath will work out of the box as a transport.

人话

可以实现消息的全局传输,通常配合着 config,当云端的配置更改之后,能够一次性更新所有微服务

7.1.2 Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

7.1.3 Use

  • 引入依赖

  • 修改 application.yml 或 bootstrap.yml

    • 服务端
1
2
3
4
5
6
7
8
9
10
11
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
management:
endpoints:
web:
exposure:
include: "bus-refresh"

7.2 Stream

7.2.1 What is Stream

官方文档

Spring Cloud Stream is a framework for building highly scalable event-driven microservices connected with shared messaging systems.

The framework provides a flexible programming model built on already established and familiar Spring idioms and best practices, including support for persistent pub/sub semantics, consumer groups, and stateful partitions.

人话

就像用 JDBC 可以操作 MySQL、Oracle 一样,Stream 是为了统一消息总线的接口而存在的,支持 rabbitMQ 和 Kafka 两大总线的通配

7.2.2 Dependency

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

7.2.3 Use

  • 引入依赖

  • 编写 application.yml

    • 服务端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
spring:
cloud:
stream:
binders: // 定义 binder
myRabbit: // 名称自定义
type: rabbit // 类型
environment: //环境
spring:
rabbitmq:
host: localhost
port: 5672 // rabbitmq 默认注册端口
username: guest // rabbitmq 默认用户名
password: guest // rabbitmq 默认密码
bindings: // 绑定
output: // 输出
destination: CyingExchange // 自定义一个名字
port: 8500 // 服务注册中心端口
discovery:
service-name: ${spring.application.name}
  • 客户端

  • ```yaml
    spring:
    cloud:

    stream:
      binders: // 定义 binder
        myRabbit: // 名称自定义
          type: rabbit // 类型
          environment: //环境
            spring:
              rabbitmq:
                host: localhost
                port: 5672 // rabbitmq 默认注册端口
                username: guest // rabbitmq 默认用户名
                password: guest // rabbitmq 默认密码
      bindings: // 绑定
        input: // 输入
          destination: CyingExchange // 自定义一个名字
          content-type: application/json // 接收的格式
          binder: myRabbit // 使用的 binder
          group: cyingOrg // 分组,避免重复消费
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    - 编写主启动

    - 编写服务端与客户端

    - 服务端

    ```java
    @Service
    @EnableBinding(Source.class) // 重点
    public class PaymentServiceImpl implements PaymentService {

    @Resource
    private MessageChannel output; // 重点

    public Payment getPaymentById(Long id) {
    output.send(MessageBuilder.withPayload(“消息”).build()); //重点
    return null;
    }
    }
  • 客户端

1
2
3
4
5
6
7
8
9
10
11
@EnableBinding(Sink.class) // 重点
@Slf4j
@Component // 重点
public class ReceiveController {

@StreamListener(Sink.INPUT) //重点
public void input(Message<String> msg) { //重点
log.info(msg.getPayload()); //重点
}

}

八、SpringCloud Alibaba

8.1 Nacos

8.1.1 What is Nacos

官方文档

Nacos is committed to help you discover, configure, and manage your microservices. It provides a set of simple and useful features enabling you to realize dynamic service discovery, service configuration, service metadata and traffic management.

Nacos makes it easier and faster to construct, deliver and manage your microservices platform. It is the infrastructure that supports a service-centered modern application architecture with a microservices or cloud-native approach.

中文版

Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。

Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。

关键特性

  • 服务发现和服务健康监测

    Nacos 支持基于 DNS 和基于 RPC 的服务发现。服务提供者使用 原生SDKOpenAPI、或一个独立的Agent TODO注册 Service 后,服务消费者可以使用DNS TODOHTTP&API查找和发现服务。

    Nacos 提供对服务的实时的健康检查,阻止向不健康的主机或服务实例发送请求。Nacos 支持传输层 (PING 或 TCP)和应用层 (如 HTTP、MySQL、用户自定义)的健康检查。 对于复杂的云环境和网络拓扑环境中(如 VPC、边缘网络等)服务的健康检查,Nacos 提供了 agent 上报模式和服务端主动检测2种健康检查模式。Nacos 还提供了统一的健康检查仪表盘,帮助您根据健康状态管理服务的可用性及流量。

  • 动态配置服务

    动态配置服务可以让您以中心化、外部化和动态化的方式管理所有环境的应用配置和服务配置。

    动态配置消除了配置变更时重新部署应用和服务的需要,让配置管理变得更加高效和敏捷。

    配置中心化管理让实现无状态服务变得更简单,让服务按需弹性扩展变得更容易。

    Nacos 提供了一个简洁易用的UI (控制台样例 Demo) 帮助您管理所有的服务和应用的配置。Nacos 还提供包括配置版本跟踪、金丝雀发布、一键回滚配置以及客户端配置更新状态跟踪在内的一系列开箱即用的配置管理特性,帮助您更安全地在生产环境中管理配置变更和降低配置变更带来的风险。

  • 动态 DNS 服务

    动态 DNS 服务支持权重路由,让您更容易地实现中间层负载均衡、更灵活的路由策略、流量控制以及数据中心内网的简单DNS解析服务。动态DNS服务还能让您更容易地实现以 DNS 协议为基础的服务发现,以帮助您消除耦合到厂商私有服务发现 API 上的风险。

    Nacos 提供了一些简单的 DNS APIs TODO 帮助您管理服务的关联域名和可用的 IP:PORT 列表.

  • 服务及其元数据管理

    Nacos 能让您从微服务平台建设的视角管理数据中心的所有服务及元数据,包括管理服务的描述、生命周期、服务的静态依赖分析、服务的健康状态、服务的流量管理、路由及安全策略、服务的 SLA 以及最首要的 metrics 统计数据。

  • 更多的特性列表 …

人话

Nacos 啊,是个很强大的框架,能够非常轻松的实现服务注册与发现、全局配置,而且配置都是在 web 端配置,配置好后立即生效

命名空间、分组和 DataId 的关系

类似于 Java 的 Module、Package、Class,从逻辑上区分配置信息

image-20200505123823244

可以通过配置 spring.cloud.nacos.config.namespace 指定命名空间,spring.cloud.nacos.config.group 指定分组

8.1.2 Dependency

服务发现

1
2
3
4
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

服务配置

1
2
3
4
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

8.1.3 Use

  • 下载并启动 nacos

8.1.3.1 服务注册

  • 引入依赖

  • 书写 applcation.yml

1
2
3
4
5
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848 // nacos 默认端口

8.1.3.2 服务配置

  • 引入依赖

  • 书写 bootstrap.yml

1
2
3
4
5
6
7
8
9
10
11
server:
port: 8081

spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml
  • 书写 application.yml

    • spring:
        profiles:
          active: dev
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34

      - 书写主启动

      - 书写 controller 并添加 @RefreshScope 注解

      - 在 Nacos 的 web 端添加配置

      - ![image-20200505123212448](http://narpro.top/img/image-20200505123212448.png)

      - ![image-20200505123410351](http://narpro.top/img/image-20200505123410351.png)

      - ![image-20200505123433046](http://narpro.top/img/image-20200505123433046.png)

      - 启动微服务,并尝试访问 /get/config 展示配置内容,试图修改一下配置内容,发布后,刷新一下 /get/config 页面,发现配置立即同步

      ## 8.2 Sentinel

      ### 8.2.1 What is Sentinel

      **官方文档 ** [链接](https://github.com/alibaba/Sentinel/wiki)

      > As distributed systems are becoming increasingly popular, the reliability between services is becoming more important than ever before. Sentinel is a powerful flow control component that takes "flow" as the breakthrough point and covers multiple fields including flow control, concurrency limiting, circuit breaking, and adaptive system protection to guarantee the reliability of microservices.

      **人话**

      > 用于替代 Hystrix 做服务限流、熔断、降级

      ### 8.2.2 Dependency

      ```xml
      <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
      </dependency>
      ### 8.2.3 Use
  • 引入依赖

  • 下载并启动 sentinel

  • 书写主启动类

  • 书写 Controller

  • 启动微服务

8.2.3.1 流量控制

image-20200426222039556

  • 资源名:url 地址
  • 针对来源:
  • 阈值类型:
    • QPS:每秒钟允许请求的次数
    • 线程数:服务器内部能同时处理的线程数
  • 单机阈值:对阈值类型设置数量
  • 是否集群
  • 流控模式:
    • 直接:对资源本身
    • 关联:资源本身繁忙,从而限制指定关联的资源
  • 流控效果:
    • 快速失败:一旦请求超过阈值(每秒请求次数超出,或者同时需要的线程数多余设置的线程数)则直接报错
    • Warm up:让服务器能承载的阈值上限逐渐上升
    • 排队等待:不管来多少请求,不会拒绝,只不过一个一个处理
8.2.3.1.1 QPS-直接-快速失败

一旦一秒内请求次数超过 QPS 能够承载的阈值,则直接服务限流【Blocked By Sentinel(flow limiting)

8.2.3.1.2 线程数-直接-快速失败

一旦同时请求的线程数超过了设置的线程数,则直接服务限流

8.2.3.1.3 QPS-关联-快速失败

如果 A 的流控关联了 B,而 A 的请求超出了所承受的最高阈值,则 B 被限流。比如 A 是支付,B 是下单,A 的支付都忙不过来,那 B 的下单利索当然要被迫限流等一等

8.2.3.1.4 QPS-直接-warm up

选择后会出现新的文本框

image-20200426224259471

冷因子默认是 3,设阈值为 10,预热时长为 5,则一开始能承载的最大阈值为 10/3=3 个请求,5 秒之后,渐渐的能承载 10 个

8.2.3.1.5 QPS-直接-排队等待

根据 QPS 的阈值,确定每秒处理多少个请求

8.2.3.2 熔断降级

image-20200426225356181

  • 资源名:url 地址
  • 降级策略:以下均是窗口期内通过的请求 >= 5 才生效
    • RT:平均响应时间(秒级),超出阈值生效。RT 最大 4900。可通过 -Dcsp.sentinel.statistic.max.rt=? 配置更高的
    • 异常比例:异常出现的比例(秒级),超过阈值生效
    • 异常数:异常出现的次数(秒级),查过阈值生效
8.2.3.2.1 RT

设 RT 为 200ms,时间窗口为 1,程序需要执行时间 1s,则发送 5 次及以上请求,这些请求还是会继续执行,但因为时间超过了 200ms,那么在下一秒将会处于降级期

8.2.3.2.2 异常比例

设异常比例为 0.2,时间窗口为 1 ,则发送 5 次及以上请求,在一秒内一旦有 20% 的请求出错,那么在下一秒将会处于降级期,而且此处只进行服务降级,即请求异常超过一定比例就降级,并不会处理异常,所以如果在没达到条件的情况下,程序抛出异常,异常将会按照规定返回给前端

8.2.3.2.3 异常数

设异常数为 10,时间窗口为 1 ,则发送 5 次及以上请求,在一分钟内,一旦有 10 个请求抛出异常,那么在下一秒内会处于降级期

8.2.3.3 热点

image-20200426233125554

  • 资源名:注解中的指定名
  • 限流模式
  • 参数索引:注解所在方法的第几个参数
  • 单位阈值:允许的请求数
  • 统计窗口时长
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@GetMapping(value = "/hotkey")
@SentinelResource(
value = "hotkey",
blockHandler = "hotkeyHandler"
)
public CommonResult<String> hotKey(
@RequestParam(value = "p1", required = false) String p1,
@RequestParam(value = "p2", required = false) String p2
) {
return new CommonResult<String>(200, "p1: " + p1 + ", p2: " + p2);
}

public CommonResult<String> hotkeyHandler(
String p1,
String p2,
BlockException e
) {
return new CommonResult<String>(
200,
"p1: " + p1 + ", p2: " + p2,
e.getMessage()
);
}

若要检测 p1,即第 0 个参数

设资源名为 hotkey,参数索引为 0,单位阈值为 1,统计窗口时长为 1,则当访问 /hotkey 时,带有 p1 的情况下,1 秒钟只能发送 1 次请求,否则就会进入 hotkeyHandler 方法进行降级处理

当热点配置成功后还能继续追加高级操作

image-20200426235645914

  • 参数类型:只支持 8 个基本类型和 String
  • 参数值:可以额外考虑的值
  • 限流阈值

设参数类型为 String,参数值为 250,限流阈值为 10,其他与上面相同,则 p1 值是 250 时,每秒要达到 10 次后才降级

8.2.3.4 @SentinelResource

8.2.3.4.1 局部
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@SentinelResource(
value = "fallback",
fallback = "getFallbackHandler", // 当程序抛出异常时执行
blockHandler = "getBlockHandler" // 当被限流熔断降级时执行
)
@GetMapping(value = "/s/get/{id}")
public CommonResult<Payment> get(@PathVariable("id") Long id) {
if (id == 3L) {
throw new IllegalArgumentException("非法参数");
}
return new CommonResult<>(200, Thread.currentThread().getName(), "Success", service.getPaymentById(id));
}

public CommonResult<Payment> getFallbackHandler(@PathVariable("id") Long id, Throwable e) {
return new CommonResult<>(404, Thread.currentThread().getName(), e.getMessage(), new Payment());
}

public CommonResult<Payment> getBlockHandler(@PathVariable("id") Long id, BlockException e) {
return new CommonResult<Payment>(404, Thread.currentThread().getName(), "Blocked By Cying", new Payment());
}
8.2.3.4.2 全局
1
2
3
4
5
6
7
public class MyGlobalHandler {

public static CommonResult<Payment> getHandler(Long id, BlockException e) {
return new CommonResult<>(404, Thread.currentThread().getName(), "请求过快", new Payment());
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class PaymentController {

@Resource
private PaymentServiceImpl service;

@SentinelResource(
value = "getPaymentById",
blockHandlerClass = MyGlobalHandler.class, // 指定类
blockHandler = "getHandler" // 指定方法
)
@GetMapping(value = "/s/get/{id}")
public CommonResult<Payment> get(@PathVariable("id") Long id) {
return new CommonResult<>(200, Thread.currentThread().getName(), "Success", service.getPayment(id));
}

}

九、附录

9.1 Eureka Properties

9.1.1 instance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#服务注册中心实例的主机名
eureka.instance.hostname=localhost
#注册在Eureka服务中的应用组名
eureka.instance.app-group-name=
#注册在的Eureka服务中的应用名称
eureka.instance.appname=
#该实例注册到服务中心的唯一ID
eureka.instance.instance-id=
#该实例的IP地址
eureka.instance.ip-address=
#该实例,相较于hostname是否优先使用IP
eureka.instance.prefer-ip-address=false
#用于AWS平台自动扩展的与此实例关联的组名,
eureka.instance.a-s-g-name=
#部署此实例的数据中心
eureka.instance.data-center-info=
#默认的地址解析顺序
eureka.instance.default-address-resolution-order=
#该实例的环境配置
eureka.instance.environment=
#初始化该实例,注册到服务中心的初始状态
eureka.instance.initial-status=up
#表明是否只要此实例注册到服务中心,立马就进行通信
eureka.instance.instance-enabled-onit=false
#该服务实例的命名空间,用于查找属性
eureka.instance.namespace=eureka
#该服务实例的子定义元数据,可以被服务中心接受到
eureka.instance.metadata-map.test = test
#服务中心删除此服务实例的等待时间(秒为单位),时间间隔为最后一次服务中心接受到的心跳时间
eureka.instance.lease-expiration-duration-in-seconds=90
#该实例给服务中心发送心跳的间隔时间,用于表明该服务实例可用
eureka.instance.lease-renewal-interval-in-seconds=30
#该实例,注册服务中心,默认打开的通信数量
eureka.instance.registry.default-open-for-traffic-count=1
#每分钟续约次数
eureka.instance.registry.expected-number-of-renews-per-min=1
#该实例健康检查url,绝对路径
eureka.instance.health-check-url=
#该实例健康检查url,相对路径
eureka.instance.health-check-url-path=/health
#该实例的主页url,绝对路径
eureka.instance.home-page-url=
#该实例的主页url,相对路径
eureka.instance.home-page-url-path=/
#该实例的安全健康检查url,绝对路径
eureka.instance.secure-health-check-url=
#https通信端口
eureka.instance.secure-port=443
#https通信端口是否启用
eureka.instance.secure-port-enabled=false
#http通信端口
eureka.instance.non-secure-port=80
#http通信端口是否启用
eureka.instance.non-secure-port-enabled=true
#该实例的安全虚拟主机名称(https)
eureka.instance.secure-virtual-host-name=unknown
#该实例的虚拟主机名称(http)
eureka.instance.virtual-host-name=unknown
#该实例的状态呈现url,绝对路径
eureka.instance.status-page-url=
#该实例的状态呈现url,相对路径
eureka.instance.status-page-url-path=/status

9.1.2 server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#服务端开启自我保护模式。无论什么情况,服务端都会保持一定数量的服务。避免client与server的网络问题,而出现大量的服务被清除。
eureka.server.enable-self-preservation=true
#开启清除无效服务的定时任务,时间间隔。默认1分钟
eureka.server.eviction-interval-timer-in-ms= 60000
#间隔多长时间,清除过期的delta数据
eureka.server.delta-retention-timer-interval-in-ms=0
#过期数据,是否也提供给client
eureka.server.disable-delta=false
#eureka服务端是否记录client的身份header
eureka.server.log-identity-headers=true
#请求频率限制器
eureka.server.rate-limiter-burst-size=10
#是否开启请求频率限制器
eureka.server.rate-limiter-enabled=false
#请求频率的平均值
eureka.server.rate-limiter-full-fetch-average-rate=100
#是否对标准的client进行频率请求限制。如果是false,则只对非标准client进行限制
eureka.server.rate-limiter-throttle-standard-clients=false
#注册服务、拉去服务列表数据的请求频率的平均值
eureka.server.rate-limiter-registry-fetch-average-rate=500
#设置信任的client list
eureka.server.rate-limiter-privileged-clients=
#在设置的时间范围类,期望与client续约的百分比。
eureka.server.renewal-percent-threshold=0.85
#多长时间更新续约的阈值
eureka.server.renewal-threshold-update-interval-ms=0
#对于缓存的注册数据,多长时间过期
eureka.server.response-cache-auto-expiration-in-seconds=180
#多长时间更新一次缓存中的服务注册数据
eureka.server.response-cache-update-interval-ms=0
#缓存增量数据的时间,以便在检索的时候不丢失信息
eureka.server.retention-time-in-m-s-in-delta-queue=0
#当时间戳不一致的时候,是否进行同步
eureka.server.sync-when-timestamp-differs=true
#是否采用只读缓存策略,只读策略对于缓存的数据不会过期。
eureka.server.use-read-only-response-cache=true

9.1.3 client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#该客户端是否可用
eureka.client.enabled=true
#实例是否在eureka服务器上注册自己的信息以供其他服务发现,默认为true
eureka.client.register-with-eureka=false
#此客户端是否获取eureka服务器注册表上的注册信息,默认为true
eureka.client.fetch-registry=false
#是否过滤掉,非UP的实例。默认为true
eureka.client.filter-only-up-instances=true
#与Eureka注册服务中心的通信zone和url地址
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

#client连接Eureka服务端后的空闲等待时间,默认为30 秒
eureka.client.eureka-connection-idle-timeout-seconds=30
#client连接eureka服务端的连接超时时间,默认为5秒
eureka.client.eureka-server-connect-timeout-seconds=5
#client对服务端的读超时时长
eureka.client.eureka-server-read-timeout-seconds=8
#client连接all eureka服务端的总连接数,默认200
eureka.client.eureka-server-total-connections=200
#client连接eureka服务端的单机连接数量,默认50
eureka.client.eureka-server-total-connections-per-host=50
#执行程序指数回退刷新的相关属性,是重试延迟的最大倍数值,默认为10
eureka.client.cache-refresh-executor-exponential-back-off-bound=10
#执行程序缓存刷新线程池的大小,默认为5
eureka.client.cache-refresh-executor-thread-pool-size=2
#心跳执行程序回退相关的属性,是重试延迟的最大倍数值,默认为10
eureka.client.heartbeat-executor-exponential-back-off-bound=10
#心跳执行程序线程池的大小,默认为5
eureka.client.heartbeat-executor-thread-pool-size=5
# 询问Eureka服务url信息变化的频率(s),默认为300秒
eureka.client.eureka-service-url-poll-interval-seconds=300
#最初复制实例信息到eureka服务器所需的时间(s),默认为40秒
eureka.client.initial-instance-info-replication-interval-seconds=40
#间隔多长时间再次复制实例信息到eureka服务器,默认为30秒
eureka.client.instance-info-replication-interval-seconds=30
#从eureka服务器注册表中获取注册信息的时间间隔(s),默认为30秒
eureka.client.registry-fetch-interval-seconds=30

# 获取实例所在的地区。默认为us-east-1
eureka.client.region=us-east-1
#实例是否使用同一zone里的eureka服务器,默认为true,理想状态下,eureka客户端与服务端是在同一zone下
eureka.client.prefer-same-zone-eureka=true
# 获取实例所在的地区下可用性的区域列表,用逗号隔开。(AWS)
eureka.client.availability-zones.china=defaultZone,defaultZone1,defaultZone2
#eureka服务注册表信息里的以逗号隔开的地区名单,如果不这样返回这些地区名单,则客户端启动将会出错。默认为null
eureka.client.fetch-remote-regions-registry=
#服务器是否能够重定向客户端请求到备份服务器。 如果设置为false,服务器将直接处理请求,如果设置为true,它可能发送HTTP重定向到客户端。默认为false
eureka.client.allow-redirects=false
#客户端数据接收
eureka.client.client-data-accept=
#增量信息是否可以提供给客户端看,默认为false
eureka.client.disable-delta=false
#eureka服务器序列化/反序列化的信息中获取“_”符号的的替换字符串。默认为“__“
eureka.client.escape-char-replacement=__
#eureka服务器序列化/反序列化的信息中获取“$”符号的替换字符串。默认为“_-”
eureka.client.dollar-replacement="_-"
#当服务端支持压缩的情况下,是否支持从服务端获取的信息进行压缩。默认为true
eureka.client.g-zip-content=true
#是否记录eureka服务器和客户端之间在注册表的信息方面的差异,默认为false
eureka.client.log-delta-diff=false
# 如果设置为true,客户端的状态更新将会点播更新到远程服务器上,默认为true
eureka.client.on-demand-update-status-change=true
#此客户端只对一个单一的VIP注册表的信息感兴趣。默认为null
eureka.client.registry-refresh-single-vip-address=
#client是否在初始化阶段强行注册到服务中心,默认为false
eureka.client.should-enforce-registration-at-init=false
#client在shutdown的时候是否显示的注销服务从服务中心,默认为true
eureka.client.should-unregister-on-shutdown=true

# 获取eureka服务的代理主机,默认为null
eureka.client.proxy-host=
#获取eureka服务的代理密码,默认为null
eureka.client.proxy-password=
# 获取eureka服务的代理端口, 默认为null
eureka.client.proxy-port=
# 获取eureka服务的代理用户名,默认为null
eureka.client.proxy-user-name=

#属性解释器
eureka.client.property-resolver=
#获取实现了eureka客户端在第一次启动时读取注册表的信息作为回退选项的实现名称
eureka.client.backup-registry-impl=
#这是一个短暂的×××的配置,如果最新的×××是稳定的,则可以去除,默认为null
eureka.client.decoder-name=
#这是一个短暂的编码器的配置,如果最新的编码器是稳定的,则可以去除,默认为null
eureka.client.encoder-name=

#是否使用DNS机制去获取服务列表,然后进行通信。默认为false
eureka.client.use-dns-for-fetching-service-urls=false
#获取要查询的DNS名称来获得eureka服务器,此配置只有在eureka服务器ip地址列表是在DNS中才会用到。默认为null
eureka.client.eureka-server-d-n-s-name=
#获取eureka服务器的端口,此配置只有在eureka服务器ip地址列表是在DNS中才会用到。默认为null
eureka.client.eureka-server-port=
#表示eureka注册中心的路径,如果配置为eureka,则为http://x.x.x.x:x/eureka/,在eureka的配置文件中加入此配置表示eureka作为客户端向注册中心注册,从而构成eureka集群。此配置只有在eureka服务器ip地址列表是在DNS中才会用到,默认为null
eureka.client.eureka-server-u-r-l-context=

9.2 Zookeeper

属性名 默认值 说明
spring.cloud.zookeeper.base-sleep-time-ms 50 重试之间等待的初始时间
spring.cloud.zookeeper.block-until-connected-unit 与Zookeeper连接时阻止的时间单位
spring.cloud.zookeeper.block-until-connected-wait 10 等待时间阻止连接到Zookeeper
spring.cloud.zookeeper.connect-string localhost:2181 连接字符串到Zookeeper集群
spring.cloud.zookeeper.default-health-endpoint 将检查以验证依赖关系是否存在的默认运行状况端点
spring.cloud.zookeeper.dependencies 将别名映射到ZookeeperDependency。从Ribbon的角度看,别名实际上是serviceID,因为Ribbon不能接受serviceID中的嵌套结构
spring.cloud.zookeeper.dependency-configurations
spring.cloud.zookeeper.dependency-names
spring.cloud.zookeeper.discovery.enabled TRUE
spring.cloud.zookeeper.discovery.instance-host 预定义的主机可以在Zookeeper中注册自己的服务。对应于URI规范中的{code address}。
spring.cloud.zookeeper.discovery.instance-port 端口注册服务(默认为侦听端口)
spring.cloud.zookeeper.discovery.metadata 获取与此实例关联的元数据名称/值对。该信息被发送到动物管理员,可以被其他实例使用。
spring.cloud.zookeeper.discovery.register TRUE 在zookeeper中注册为服务。
spring.cloud.zookeeper.discovery.root /services 所有实例都被注册的根Zookeeper文件夹
spring.cloud.zookeeper.discovery.uri-spec {scheme}://{address}:{port} 在Zookeeper服务注册期间解决的URI规范
spring.cloud.zookeeper.enabled TRUE 启用Zookeeper
spring.cloud.zookeeper.max-retries 10 最多重试次数
spring.cloud.zookeeper.max-sleep-ms 500 每次重试最多可以以ms为单位睡眠
spring.cloud.zookeeper.prefix 将应用于所有Zookeeper依赖关系的路径的公共前缀

9.3 Consul

属性名 默认值 说明
spring.cloud.consul.discovery.acl-token
spring.cloud.consul.discovery.catalog-services-watch-delay 10
spring.cloud.consul.discovery.catalog-services-watch-timeout 2
spring.cloud.consul.discovery.default-query-tag 如果没有在serverListQueryTags中列出,请在服务列表中查询标签。
spring.cloud.consul.discovery.default-zone-metadata-name zone 服务实例区域来自元数据。这允许更改元数据标签名称。
spring.cloud.consul.discovery.enabled TRUE 是否启用服务发现
spring.cloud.consul.discovery.fail-fast TRUE 在服务注册期间抛出异常,如果为true,否则,记录警告(默认为true)。
spring.cloud.consul.discovery.health-check-interval 10 执行健康检查的频率(例如10s)
spring.cloud.consul.discovery.health-check-path /health 调用健康检查的备用服务器路径
spring.cloud.consul.discovery.health-check-timeout 10 健康检查超时(例如10s)
spring.cloud.consul.discovery.health-check-url 自定义健康检查网址覆盖默认值
spring.cloud.consul.discovery.heartbeat.enabled FALSE
spring.cloud.consul.discovery.heartbeat.heartbeat-interval
spring.cloud.consul.discovery.heartbeat.interval-ratio
spring.cloud.consul.discovery.heartbeat.ttl-unit s
spring.cloud.consul.discovery.heartbeat.ttl-value 30
spring.cloud.consul.discovery.host-info
spring.cloud.consul.discovery.hostname 访问服务器时使用的主机名
spring.cloud.consul.discovery.instance-id 唯一的服务实例ID
spring.cloud.consul.discovery.instance-zone 服务实例区
spring.cloud.consul.discovery.ip-address 访问服务时使用的IP地址(还必须设置preferIpAddress才能使用)
spring.cloud.consul.discovery.lifecycle.enabled TRUE
spring.cloud.consul.discovery.management-port 端口注册管理服务(默认为管理端口)
spring.cloud.consul.discovery.management-suffix management 注册管理服务时使用后缀
spring.cloud.consul.discovery.management-tags 注册管理服务时使用的标签
spring.cloud.consul.discovery.port 端口注册服务(默认为侦听端口)
spring.cloud.consul.discovery.prefer-agent-address FALSE 我们将如何确定使用地址的来源
spring.cloud.consul.discovery.prefer-ip-address FALSE 在注册时使用ip地址而不是主机名
spring.cloud.consul.discovery.query-passing FALSE 将“pass”参数添加到/ v1 / health / service / serviceName。这会将健康检查推送到服务器。
spring.cloud.consul.discovery.register TRUE 注册为领事服务。
spring.cloud.consul.discovery.register-health-check TRUE 注册领事健康检查。在开发服务期间有用。
spring.cloud.consul.discovery.scheme http 是否注册http或https服务
spring.cloud.consul.discovery.server-list-query-tags 服务器列表中要查询的serviceId的→标签的映射。这允许通过单个标签过滤服务。
spring.cloud.consul.discovery.service-name 服务名称
spring.cloud.consul.discovery.tags 注册服务时使用的标签
spring.cloud.consul.enabled TRUE 启用了spring cloud consul
spring.cloud.consul.host localhost Consul代理主机名。默认为“localhost”。
spring.cloud.consul.port 8500 Consul代理端口。默认为’8500’。
spring.cloud.consul.retry.initial-interval 1000 初始重试间隔(以毫秒为单位)。
spring.cloud.consul.retry.max-attempts 6 最大尝试次数。
spring.cloud.consul.retry.max-interval 2000 退避的最大间隔
spring.cloud.consul.retry.multiplier 1.1 下一个间隔的乘数。

9.4 Config

属性名 默认值 说明
spring.cloud.config.allow-override TRUE 标记以指示可以使用{@link #isSystemPropertiesOverride()systemPropertiesOverride}。设置为false以防止用户意外更改默认值。默认值为true。
spring.cloud.config.authorization 客户端使用的授权令牌连接到服务器。
spring.cloud.config.discovery.enabled FALSE 标记以指示启用配置服务器发现(配置服务器URL将通过发现查找)。
spring.cloud.config.discovery.service-id configserver 服务ID来定位配置服务器。
spring.cloud.config.enabled TRUE 标记说远程配置启用。默认为true;
spring.cloud.config.fail-fast FALSE 标记表示无法连接到服务器是致命的(默认为false)。
spring.cloud.config.label 用于拉取远程配置属性的标签名称。默认设置在服务器上(通常是基于git的服务器的“主”)。
spring.cloud.config.name 用于获取远程属性的应用程序名称。
spring.cloud.config.override-none FALSE 标志表示当{@link #setAllowOverride(boolean)allowOverride}为true时,外部属性应该采用最低优先级,并且不覆盖任何现有的属性源(包括本地配置文件)。默认为false。
spring.cloud.config.override-system-properties TRUE 标记以指示外部属性应覆盖系统属性。默认值为true。
spring.cloud.config.password 联系远程服务器时使用的密码(HTTP Basic)。
spring.cloud.config.profile default 获取远程配置时使用的默认配置文件(逗号分隔)。默认为“默认”。
spring.cloud.config.retry.initial-interval 1000 初始重试间隔(以毫秒为单位)。
spring.cloud.config.retry.max-attempts 6 最大尝试次数。
spring.cloud.config.retry.max-interval 2000 退避的最大间隔
spring.cloud.config.retry.multiplier 1.1 下一个间隔的乘数。
spring.cloud.config.server.bootstrap FALSE 表示配置服务器应使用远程存储库中的属性初始化其自己的环境。默认情况下关闭,因为它会延迟启动,但在将服务器嵌入到另一个应用程序中时很有用。
spring.cloud.config.server.default-application-name application 传入请求没有特定的默认应用程序名称。
spring.cloud.config.server.default-label 传入请求没有特定标签时的默认存储库标签。
spring.cloud.config.server.default-profile default 传入请求没有特定的默认应用程序配置文件时。
spring.cloud.config.server.encrypt.enabled TRUE 在发送给客户端之前启用对环境属性的解密。
spring.cloud.config.server.git.basedir 库的本地工作副本的基本目录。
spring.cloud.config.server.git.clone-on-start 标记以表明应该在启动时克隆存储库(不是按需)。通常会导致启动速度较慢,但第一次查询更快。
spring.cloud.config.server.git.default-label
spring.cloud.config.server.git.environment
spring.cloud.config.server.git.force-pull 标记表示存储库应该强制拉。如果真的丢弃任何本地更改并从远程存储库获取。
spring.cloud.config.server.git.git-factory
spring.cloud.config.server.git.password 使用远程存储库验证密码。
spring.cloud.config.server.git.repos 存储库标识符映射到位置和其他属性。
spring.cloud.config.server.git.search-paths 在本地工作副本中使用的搜索路径。默认情况下只搜索根。
spring.cloud.config.server.git.timeout 用于获取HTTP或SSH连接的超时(以秒为单位)(如果适用)。默认5秒。
spring.cloud.config.server.git.uri 远程存储库的URI。
spring.cloud.config.server.git.username 用于远程存储库的身份验证用户名。
spring.cloud.config.server.health.repositories
spring.cloud.config.server.native.fail-on-error FALSE 标识以确定在解密期间如何处理异常(默认为false)。
spring.cloud.config.server.native.search-locations [] 搜索配置文件的位置。默认与Spring Boot应用程序相同,因此[classpath:/,classpath:/ config /,file:./,file:./ config /]。
spring.cloud.config.server.native.version 为本地存储库报告的版本字符串
spring.cloud.config.server.overrides 无条件发送给所有客户的资源的额外地图。
spring.cloud.config.server.prefix 配置资源路径的前缀(默认为空)。当您不想更改上下文路径或servlet路径时嵌入其他应用程序时很有用。
spring.cloud.config.server.strip-document-from-yaml TRUE 标记为指示作为文本或集合(而不是映射)的YAML文档应以“本机”形式返回。
spring.cloud.config.server.svn.basedir 库的本地工作副本的基本目录。
spring.cloud.config.server.svn.default-label trunk 用于环境属性请求的默认标签。
spring.cloud.config.server.svn.environment
spring.cloud.config.server.svn.password 使用远程存储库验证密码。
spring.cloud.config.server.svn.search-paths 在本地工作副本中使用的搜索路径。默认情况下只搜索根。
spring.cloud.config.server.svn.uri 远程存储库的URI。
spring.cloud.config.server.svn.username 用于远程存储库的身份验证用户名。
spring.cloud.config.token 安全令牌通过到底层环境库。
spring.cloud.config.uri http://localhost:8888 远程服务器的URI(默认http:// localhost:8888)。
spring.cloud.config.username 联系远程服务器时使用的用户名(HTTP Basic)。
spring.cloud.consul.config.acl-token
spring.cloud.consul.config.data-key data 如果格式为Format.PROPERTIES或Format.YAML,则使用以下字段来查找协调配置。
spring.cloud.consul.config.default-context application
spring.cloud.consul.config.enabled TRUE
spring.cloud.consul.config.fail-fast TRUE 在配置查找期间抛出异常,如果为true,否则为日志警告。
spring.cloud.consul.config.format
spring.cloud.consul.config.prefix config
spring.cloud.consul.config.profile-separator ,
spring.cloud.consul.config.watch.delay 1000 手表的固定延迟的价值在毫秒。默认为1000。
spring.cloud.consul.config.watch.enabled TRUE 如果手表启用 默认为true。
spring.cloud.consul.config.watch.wait-time 55 等待(或阻止)观看查询的秒数,默认为55.需要小于默认的ConsulClient(默认为60)。要增加ConsulClient超时,使用自定义的HttpClient创建一个带有自定义ConsulRawClient的ConsulClient bean。

9.5 Stream

属性名 默认值 说明
spring.cloud.stream.binders
spring.cloud.stream.bindings
spring.cloud.stream.consul.binder.event-timeout 5
spring.cloud.stream.consumer-defaults
spring.cloud.stream.default-binder
spring.cloud.stream.dynamic-destinations []
spring.cloud.stream.ignore-unknown-properties TRUE
spring.cloud.stream.instance-count 1
spring.cloud.stream.instance-index 0
spring.cloud.stream.producer-defaults
spring.cloud.stream.rabbit.binder.admin-adresses []
spring.cloud.stream.rabbit.binder.compression-level 0
spring.cloud.stream.rabbit.binder.nodes []
spring.cloud.stream.rabbit.bindings