【SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式,系统详解springcloud微服务技术栈课程|黑马程序员Java微服务】
断路器熔断策略有三种:慢调用、异常比例、异常数
解读:RT超过500ms的调用是慢调用,统计最近10000ms内的请求,如果请求量超过10次,并且慢调用比例不低于0.5,则触发熔断,熔断时长为5秒。然后进入half-open状态,放行一次请求做测试。
【不废话、实践看看】
【案例】熔断策略-慢调用
需求:给 UserClient的查询用户接口设置降级规则,慢调用的RT阈值为50ms,统计时间为1秒,最小请求数量为5,失败阈值比例为0.4,熔断时长为5
提示:为了触发慢调用规则,我们需要修改UserService中的业务,增加业务耗时:
【修改controller】
package cn.itcast.user.web;import cn.itcast.user.config.PatternProperties;
import cn.itcast.user.pojo.User;
import cn.itcast.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;@Slf4j
@RestController
@RequestMapping("/user")
// @RefreshScope
public class UserController {@Autowiredprivate UserService userService;// @Value("${pattern.dateformat}")// private String dateformat;@Autowiredprivate PatternProperties properties;@GetMapping("prop")public PatternProperties properties(){return properties;}@GetMapping("now")public String now(){return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()));}/*** 路径: /user/110** @param id 用户id* @return 用户*/@GetMapping("/{id}")public User queryById(@PathVariable("id") Long id,@RequestHeader(value = "Truth", required = false) String truth) throws InterruptedException {if (id == 1){//休眠,触发熔断Thread.sleep(60);}return userService.queryById(id);}
}
重启user 服务
OK
现在测试访问,看看请求时间
id =1 ,肯定是60ms ↑
id ≠ 1
就非常快
OK,即101 会触发,102 和其他不会触发
先把之前配的流控规则删掉
直接新增
OK
手动测试…
一秒5 次,触发熔断【这就是慢调用熔断策略】