四、降级方法跟业务逻辑放在一起导致耦合度较高。我们拿服务消费者为例,进行解耦。
只需要为 Fegin 客户端的接口添加一个服务降级处理的实现类即可实现解耦
- 新增 OpenFeginService 的实现类 OpenFeginFallBackService,作为服务降级调用
@Component
public class OpenFeginFallBackService implements OpenFeginService{
@Override
public String hello(String name) {
return "系统错误---OpenFeginFallBackService fall back ,hello";
}
@Override
public String testTimeOut(String name) {
return "系统错误---OpenFeginFallBackService fall back ,testTimeOut";
}
@Override
public String providerOK(String name) {
return "系统错误---OpenFeginFallBackService fall back ,providerOK";
}
@Override
public String providerTimeOut(String name) {
return "系统错误---OpenFeginFallBackService fall back ,providerTimeOut";
}
}
- 修改 OpenFeginService 设置 fallback 处理类
@FeignClient(value = "CLOUD-PROVIDER",fallback = OpenFeginFallBackService.class)
@Component
@FeignClient(value = "CLOUD-PROVIDER",fallback = OpenFeginFallBackService.class) //服务名
public interface OpenFeginService {
@GetMapping(value = "/provider/hello/{name}")
public String hello(@PathVariable("name") String name);
@GetMapping(value = "/provider/timeout/{name}")
public String testTimeOut(@PathVariable("name") String name);
@GetMapping(value = "/provider/hystrix/ok/{name}")
public String providerOK(@PathVariable("name") String name);
@GetMapping(value = "/provider/hystrix/timeout/{name}")
public String providerTimeOut(@PathVariable("name") String name);
}
- 编写Controller 测试
@RestController
public class CHystrixFallBackController {
@Resource
private OpenFeginService service;
@GetMapping("/consumer/hystrix/fallback/hello/{name}")
public String hello(@PathVariable("name") String name){
int a=10/0;
return service.hello(name)+"CHystrixFallBackController";
}
}
- 测试
- 开启消费段服务,关闭提供方服务,服务降级测试
测试成功.png此时服务端 provider 已经down 了,但是我们做了服务降级处理,让客户端在服务端不可用时也会获取提示信心而不会耗死服务器。
- int a=10/0; 情况,服务降级测试
修改服务端,Controller 代码,使之报错,看是否客户端这边进行了降级处理
@RestController
public class ProviderController {
@Value("${server.port}")
private String port;
@RequestMapping("/provider/hello/{name}")
public String hello(@PathVariable("name") String name){
int a=10/0;
return name+" Welcome - ProviderController "+port;
}
调用,发现自动处理服务降级
a=10/0情况降级 .png
网友评论