千家信息网

Spring Cloud中Feign与Hystrix整合的示例分析

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,这篇文章给大家分享的是有关Spring Cloud中Feign与Hystrix整合的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。Feign与Hystrix整合Fe
千家信息网最后更新 2026年11月03日Spring Cloud中Feign与Hystrix整合的示例分析

这篇文章给大家分享的是有关Spring Cloud中Feign与Hystrix整合的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

Feign与Hystrix整合

Feign对Hystrix提供了支持,为"服务调用者"加入以下Feign依赖:

                    org.springframework.cloud            spring-cloud-starter-feign        

在application.yml中打开Feign的Hystrix开关,请见以下配置:

feign:  hystrix:    enabled: true

在应用启动类里面,加入开Feign的开关,本小节的"服务调用者"应用启动类,所使用的注解如下:

@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreaker@ServletComponentScan@EnableFeignClients

新建Feign接口,调用"服务提供者(spring-hystrix-provider)"的"/hello"服务,请见代码清单6-24。

代码清单6-24:

codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\feign\HelloClient.java

@FeignClient(name = "spring-hystrix-provider", fallback = HelloClientFallback.class)public interface HelloClient {    @RequestMapping(method = RequestMethod.GET, value = "/hello")    public String hello();    @Component    static class HelloClientFallback implements HelloClient {        public String hello() {            System.out.println("hello 方法的回退");            return "error hello";        }    }}

与普通的Feign客户端无异,仅仅设置了处理回退的类,回退类实现了客户端接口。为了能测试效果,修改服务器端的"/hello"服务,让其有800毫秒的延时。根据前面章节可知,默认情况下,Hystrix的超时时间为1秒,因此,还需要修改配置超时配置。代码清单6-25,在application.yml中修改命令配置。

代码清单6-25:codes\06\6.4\spring-hystrix-invoker\src\main\resources\application.yml

hystrix:  command:    HelloClient#hello():      execution:        isolation:          thread:             timeoutInMilliseconds: 500      circuitBreaker:        requestVolumeThreshold: 3

注意,如果是针对全局配置,则使用与下面类似的配置片断:

hystrix.command.default.circuitBreaker.requestVolumeThreshold // 默认时间段内发生的请求数hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds // 超时时间

如果针对某个客户端,如使用下面的配置片断:

hystrix.command.CommandKey.circuitBreaker.requestVolumeThreshold

Feign与Hystrix整合使用时,会自动帮我们生成CommandKey,格式为:"Feign客户端接口名#方法名()"。例如本例中的客户端为HelloClient,方法为hello,生成的CommandKey为"HelloClient#hello()"。而默认情况下,生成的GroupKey为@FeignClient注解的name属性。

以上的配置中,我们针对了hello方法,设置了超时时间为500毫秒,而"/hello"服务超时时间为800毫秒,换言之,hello方法总会超时。另外,如果请求超过3次并且失败率超过50%,断路器将被打开。编写控制器,调用hello服务,并查看断路器的情况,请见代码清单6-26。

代码清单6-26:HelloController.java

@RestControllerpublic class HelloController {    @Autowired    HelloClient helloClient;    @RequestMapping(value = "/feign/hello", method = RequestMethod.GET)    public String feignHello() {        // hello方法会超时        String helloResult = helloClient.hello();        // 获取断路器        HystrixCircuitBreaker breaker = HystrixCircuitBreaker.Factory                .getInstance(HystrixCommandKey.Factory                        .asKey("HelloClient#hello()"));                System.out.println("断路器状态:" + breaker.isOpen());        return helloResult;    }}

控制器的方法中,获取了hello方法的断路器,并输出其状态。接下来,编写一个测试客户端,多线程访问:http://localhost:9000/feign/hello/{index},也就是控制器的feignHello方法,客户端请见代码清单6-27。

代码清单6-27:

06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\feign\TestFeignClient.java

public class TestFeignClient {        public static void main(String[] args) throws Exception {        // 创建默认的HttpClient        final CloseableHttpClient httpclient = HttpClients.createDefault();                // 调用多次服务并输出结果        for(int i = 0; i < 6; i++) {            // 建立线程访问接口            Thread t = new Thread() {                public void run() {                    try {                        String url = "http://localhost:9000/feign/hello";                        // 调用 GET 方法请求服务                        HttpGet httpget = new HttpGet(url);                        // 获取响应                        HttpResponse response = httpclient.execute(httpget);                        // 根据 响应解析出字符串                        System.out.println(EntityUtils.toString(response.getEntity()));                    } catch (Exception e) {                        e.printStackTrace();                    }                }            };            t.start();        }        // 等待完成        Thread.sleep(15000);    }}

完成后,依次启动Eureka服务器、服务提供者、服务调用者,运行代码清单6-27,可看到"服务计用者"的控制台输出如下:

断路器状态:false断路器状态:false断路器状态:false断路器状态:false断路器状态:true断路器状态:true

根据输出可知,断路器已经被打开。

感谢各位的阅读!关于"Spring Cloud中Feign与Hystrix整合的示例分析"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

服务 断路器 方法 代码 清单 状态 配置 客户 客户端 时间 整合 接口 用者 控制 输出 情况 控制器 生成 示例 分析 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 伟宏互联网科技 广州百单互联网科技有限公司 互联网的科技 平安科技 互联网 南京欣网互联网科技 电子科技大学互联网 成都狮子座互联网科技 互联网养老 桔豆科技 青岛中康互联网医疗科技有限公司 中盈科技互联网信息有限公司 字节跳动和互联网科技 湖南诚度互联网科技有限公司 互联网科技扶贫时间 亳州好赞互联网科技有限公司 朱啸虎曾投资哪些互联网科技企业 锡山区互联网智能科技产品供应 风投北京互联网科技 上海乐五互联网科技有限公司 宁波跨境商互联网科技有限公司 抖集互联网科技技术咨询 易互联网科技有限公司 致聘互联网科技 奔汉互联网科技 老年人脱离互联网科技的作文 互联网实体化科技化 广州优美互联网科技 栖莱科技互联网股份有限公司 互联网经济与金融科技 哈尔滨屹滨互联网科技有限公司 艺电能源互联网科技有限公司招聘
0