- 全局服务降级
类上添加
@DefaultProperties(defaultFallback = "myFallback")
方法上添加
@HystrixCommand
实现回调方法
public String myFallback(){ return "降级处理了111"; }
- 设置访问的超时时间
官方给的时间是1s
针对某个方法
@HystrixCommand(commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="25000") })
全局设置时间
hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 5000
针对某个服务设定时间
hystrix: command: provider02: execution: isolation: thread: timeoutInMilliseconds: 5000
3.熔断机制
当服务出现是好时坏的现象。
我们把服务设定为三种状态:
闭合状态:服务可以正常访问
断开状态:服务不能不可以访问
半开状态:服务从不可访问到可以访问的过程
circuitBreakerRequestVolumeThreshold = 20; 统计请求的次数
circuitBreakerSleepWindowInMilliseconds = 5000; 休眠关闭的时间
circuitBreakerErrorThresholdPercentage = 50; 请求失败的闸值
当统计20次请求,如果有50%,不能访问。就会出在断开状态。经过五秒的休眠,
进入半开状态,这个时候进行统计。如果统计20次,有超过50%可以访问,进入闭合状态。
否则,进入断开状态。
在方法上,设置统计熔断的条件
@HystrixCommand(commandProperties = { @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="25000"), @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"), @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"), @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60") })
设置熔断的时间,需要是重试时间的2倍+1s。
学习Fegin
- 什么是Fegin
- 为什么要有Feign
Fegin为了解决访问代码的重复问题
- 如何实现
- 添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
修改属性文件- 修改启动类
@EnableFeignClients
- 4.实现代码
/** * 分析请求包含的内容 * 1.服务id * 2.访问路径 * 3.参数 */
@FeignClient("provider03") public interface UserFeignClient { @GetMapping("/") User getUserById(int id); }
Controll中
User user = userFeignClient.getUserById(id);
实现负载均衡
在feign包含了ribbon
只用在yml中设置某个服务支持ribbon
provider03: ribbon: ConnectTimeout: 250 # 连接超时时间(ms) ReadTimeout: 1000 # 通信超时时间(ms) OkToRetryOnAllOperations: true # 是否对所有操作重试 MaxAutoRetriesNextServer: 1 # 同一服务不同实例的重试次数 MaxAutoRetries: 1 # 同一实例的重试次数
实现Hystrix功能
怎么做
添加依赖- 修改属性文件
feign:
hystrix:
enabled: true # 开启Feign的熔断功能
修改启动类- 代码实现
@Component public class UserFeignClientCallBack implements UserFeignClient { @Override public User getUserById(int id) { User user = new User(); user.setName("我降级了"); return user; } }
@FeignClient(value = "provider03",fallback = UserFeignClientCallBack.class) public interface UserFeignClient { @GetMapping("/") User getUserById(int id); }