1。在pom文件添加相关依赖:
4.0.0 cn.edu.tju springcloudcircuitbreakerfeign 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.2.6.RELEASE 3.6.1 2.10 UTF-8 UTF-8 1.8 2020.0.2 org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.cloud spring-cloud-starter-circuitbreaker-resilience4j org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-commons 2.2.9.RELEASE org.springframework.cloud spring-cloud-starter-openfeign 3.0.2
2.在配置文件application.properties里开启feign的circuit breaker支持:
feign.circuitbreaker.enabled=true server.port=8091
3.在启动类加上@EnableFeignClients注解
4.编写FeignClient接口,(可以使其抛出错误来进行测试,比如在RequestMapping里配置一个不存在的地址)
@FeignClient(name = "demoservice", url = "http://139.198.xx.xx:9301", fallback = Fallback.class)
public interface TestClient {
@RequestMapping(method = RequestMethod.GET, value = "/test")
String getTime();
}
5.和上一个类的同一个文件里编写用来进行熔断处理的类:
@Component
class Fallback implements TestClient {
public String getTime() {
return "exception caught when getting time.";
}
}
6.编写控制器类,调用Feign接口
package cn.edu.tju.controller;
import cn.edu.tju.service.TestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private TestClient testClient;
@RequestMapping("/hi")
public String test(){
String result=testClient.getTime();
return result;
}
}
7.运行主类,访问接口:http://localhost:8091/hi,输出如下,
可以看到熔断逻辑被执行了



