1.OpenFegin
在使用restTemplate访问远程接口的时候,我们难以将接口管理起来,当接口变动的时候我们可能会修改多处。Spring Cloud 提供OpenFeign来解决这个问题。
2.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3.相应配置
@EnableFeignClients //启动类上添加相应注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4.访问请求
//name:注册在注册中心的服务名
@Component
@FeignClient(name = "demoprovider-server")
public interface DemoProvideFeignClient {
@GetMapping("/demo/text")//访问的路径 不需要携带请求地址
Result create();
}
@GetMapping("/create")
public Result test(){
return ResultHelper.newSuccessResult(
demoProvideFeignClient.create());
}
5.使用浏览器访问http://localhost:8080/create
{
"code":200,
"msg":"访问demo微服务成功",
"data":null
}
6.存在问题
当服务提供者服务宕机或者访问出现问题时,当前服务无法感知对应错误并进行判断。
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Mar 02 13:40:33 CST 2021
There was an unexpected error (type=Internal Server Error, status=500).
解决方案:Hystrix
使用Hystrix进行熔断,结合Openfeign使用,在访问第三方服务时访问超时时可进行其他处理
7.熔断处理
//导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
//添加注解
@EnableHystrix
public class DemoApplication {
}
//需要进行熔断处理的方法添加
//testTimeOutFallbackMethod 就是熔断处理后会返回的对象
@HystrixCommand(fallbackMethod = "testTimeOutFallbackMethod",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500") //3秒钟以内就是正常的业务逻辑
})
public Result method(){
xxx
xxx
xxx
return result;
}
eg:
public Result testTimeOutFallbackMethod(Throwable e)){
return ResultHelper.newErrorResult(101,"调用服务失败");
}
- 使用浏览器访问对应url,feignClient在访问另一个微服务时如果请求超时会执行testTimeOutFallbackMethod返回
{
"code":101,
"msg":"调用服务失败",
"data":null
}