SpringCoud OpenFegin

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,"调用服务失败");
    }
   
    
  1. 使用浏览器访问对应url,feignClient在访问另一个微服务时如果请求超时会执行testTimeOutFallbackMethod返回
{
"code":101,
"msg":"调用服务失败",
"data":null
}

结束

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值