ribbon

ribbon 提供了负载平衡和重试性能, 它底层是应用 RestTemplate 进行 Rest api 调用

RestTemplate

RestTemplate是SpringBoot提供的一个Rest近程调用工具
它的罕用办法:
getForObject() 执行get申请
postForObject() 执行post申请

ribbon负载平衡和重试

Ribbon负载平衡

RestTemplate 设置 @LoadBalanced

@LoadBalanced 负载平衡注解,会对 RestTemplate 实例进行封装,创立动静代理对象,并切入(AOP)负载平衡代码,把申请散发到集群中的服务器

ribbon重试


1.增加spring-retry依赖
2.ribbon:
MaxAutoRetriesNextServer: 2
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
OkToRetryOnAllOperations=true
默认只对GET申请重试, 当设置为true时, 对POST等所有类型申请都重试
MaxAutoRetriesNextServer
更换实例的次数
MaxAutoRetries
以后实例重试次数,尝试失败会更换下一个实例

Hystrix断路器


微服务宕机时,ribbon无奈转发申请

增加hystrix依赖

批改application.yml

string:
application:

name: hystrix

主程序增加 @EnableCircuitBreaker启用hystrix断路器

启动断路器,断路器提供两个外围性能:

  • 降级,超时、出错、不可达到时,对服务降级,返回错误信息或者是缓存数据
  • 熔断,当服务压力过大,谬误比例过多时,熔断所有申请,所有申请间接降级
  • 能够应用 @SpringCloudApplication 注解代替三个注解

在contller中增加降级办法例如getItems()中增加getItemsFB()
增加 @HystrixCommand 注解,指定降级办法名

hystrix超时设置

hystrix期待超时后, 会执行降级代码, 疾速向客户端返回降级后果, 默认超时工夫是1000毫秒

为了测试 hystrix 降级,咱们把 hystrix 期待超时设置得十分小(500毫秒)

此设置个别应大于 ribbon 的重试超时时长,例如 10 秒
hystrix:
command:

default:  execution:    isolation:      thread:        timeoutInMilliseconds: 500

hystrix dashboard断路器仪表盘

hystrix 对申请的降级和熔断,能够产生监控信息,hystrix dashboard能够实时的进行监控
actuator 是 spring boot 提供的服务监控工具,提供了各种监控信息的监控端点

management.endpoints.web.exposure.include 配置选项,
能够指定端点名,来裸露监控端点

如果要裸露所有端点,能够用 “*”

1.增加autuator依赖
2.management:
endpoints:

web:  exposure:    include: hystrix.stream

拜访actuator门路 查看监控端点

http://localhost:端口号/actuator

Hystrix dashboard仪表盘


1.增加依赖 Hystrix Dashboard
和Eureka Discovery Client
2.yml配置
hystrix:
dashboard:

proxy-stream-allow-list: localhost

3.主程序增加### @EnableHystrixDashboard@EnableDiscoveryClient

Feign集成Hystrix

默认不启用Hystrix,Feign不举荐启用hystrix
如果有非凡需要要启用hystrix,首先做根底配置
1.增加hystrix的残缺依赖
2.增加@EnableCircuiBreaker
3.yml配置feign.hystrix.enabled=true

降级

在申明式客户端接口的注解中,指定一个降级类
降级类要作为申明式客户端接口的子类来定义

hystrix监控

用actuator裸露hystrix.stream监控端点
1.actuator依赖
2.裸露监控端点
m.e.w.e.i=hystrix.stream
3.http://localhost:3001/actuator/hystrix.stream
4.通过调用后盾服务,
监控代码 ab -n 20000 -c 10 http:localhost:3001/user-service/7