Spring Cloud 学习笔记(4) 声明式服务调用Feign

1. 背景

2.知识

Feign 是一个声明式的REST客户端网络请求的框架,类似于 RestTemplate。它整合 了 Ribbon 与 Hystrix, 还提供了一 种声明式的 Web 服务客户端定义方式。也就是自带客户端负载均衡和断路器。

对比于RestTemplate 具有这些特点:

  • 声明式调用更清晰
  • 封装比较好:自带负载均衡和断路器
  • 方便配置

feign 在默认情况下使用 JDK 原生的 URLConnection 发送HTTP请求,也可以配置更换。

使用Feign
要使用Feign,创建一个接口并对其进行注解就行了。

3. 示例

1) 导入依赖包

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
    // 要想让 熔断起效,这里也要引用 netflix-hystrix'
    implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-netflix-hystrix', version: '2.2.8.RELEASE'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

注意:要想看到 断路器 hystrix 效果,一定要加上 spring-cloud-starter-netflix-hystrix 依赖。原因是,虽然feign可以附加断路器的实现fallback处理,但缺少hystrix包,我在这里卡了好久。切记要加上

2) 导入

写一个 feign 的客户端调用类,它用 注解声明的方式来调用 远程服务。

@FeignClient(value = "HELLO-SERVICE-1", fallbackFactory = TestFallbackFactory.class)
public interface HelloClient {

    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    String hello();

}

其中: HELLO-SERVICE-1 是 远程服务 的名称。 /hello 指向了访问的URL。主要参数也要一致。

3) 断路器 fallback 的实现

当发生超时,远程服务不可用等情形,就要出发 服务降级。我们加上一个 fallback 的降级处理方法。注解这么写
fallbackFactory = TestFallbackFactory.class

代码如下:

@Component
public class TestFallbackFactory implements FallbackFactory<HelloClient> {
    private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);

    @Override
    public HelloClient create(Throwable cause) {
        logger.info("**********");
        cause.printStackTrace();

        return new MyFallback();
    }

}


public class MyFallback implements HelloClient {
    @Override
    public String hello() {
        //throw new NoFallbackAvailableException("Boom!", new RuntimeException());
        return "出错了";
    }
}

4) 配置中开启 断路器

关键的是要在配置文件中写“ feign.circuitbreaker.enabled=true
”,将断路器开启。

server.port=9001
spring.application.name=consumer
eureka.client.serviceUrl.defaultZone=http://peer1:1111/eureka/

feign.circuitbreaker.enabled=true

#hystrix.command.default.execution.isolation.thread.timeoutinMilliseconds=2OOO

上面的负载均衡器客户机将希望发现“stores”服务的物理地址

4. 扩展

我的代码示例:https://github.com/vir56k/demo/tree/master/springboot/feign_demo

5.参考:

《Spring Cloud微服务实战》https://zhuanlan.zhihu.com/p/149693905?from_voters_page=truehttps://spring.io/projects/spring-cloud-openfeign

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值