Feign自带断路器,在配置文件中将其打开就可以
application.properties
feign.hystrix.enabled=true
application.yml
feign:
hystrix:
enabled : true
同样的,我们要先搞定服务注册中心,并将其启动。在我的项目中它的位置是

接着我将我的服务提供者启动

接下来我们开始Feign实现断路器
一、新建module



接下来next-finish。
之后feign这个module里面的架构这样的

先看配置文件application.yml
server:
port: 8764
eureka:
client:
service-url:
defaultZone: http://localhost:8760/eureka/
spring:
application:
name: service-feign
feign:
hystrix:
enabled : true
接着看SchedualServiceHello.java,其中value是微服务的名称这里指定是上诉服务提供者的服务名称可看下图。fallback标记容错后执行的类。
package com.feign.feign.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @Author zhaomengxia
* @create 2019/8/27 20:42
*/
@FeignClient(value = "service-producer",fallback = SchedualServiceHelloHystric.class)
public interface SchedualServiceHello {
@RequestMapping(value = "/hello",method = RequestMethod.GET)
String sayHello(@RequestParam("name") String name);
}
再看SchedualServiceHello接口的实现类SchedualServiceHelloHystric.java
package com.feign.feign.service;
import org.springframework.stereotype.Component;
/**
* @Author zhaomengxia
* @create 2019/8/27 20:52
*/
@Component
public class SchedualServiceHelloHystric implements SchedualServiceHello{
@Override
public String sayHello(String name) {
return "sorry,"+name;
}
}
最后是启动类FeignApplication.java
package com.feign.feign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
下面就启动FeignApplication

此时浏览器访问http://localhost:8764/sayHello?name=xia

将服务提供者service-producer关闭
之后访问http://localhost:8764/sayHello?name=xia

源代码
本文介绍了如何在Spring Cloud Feign中启用断路器功能,通过配置文件开启断路器,并逐步展示了从创建新模块、编写配置文件、定义接口及实现类,到启动应用的过程。当服务提供者关闭时,断路器能够起到容错作用,避免服务雪崩。

被折叠的 条评论
为什么被折叠?



