1. 引入依赖
引入Feign和Hystrix依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix</artifactId>
</dependency>
2. 修改配置
消费者配置中添加
feign.hystrix.enabled=true
3. 修改启动类
启动类中添加注解
//开启Feign
@EnableFeignClients
//开启断路器
@EnableCircuitBreaker
4. 编写代码
消费者Controller层
@RestController
public class MyController {
@Autowired
private HelloService hs;
@RequestMapping("/test")
public String test(String name) {
return hs.hello(name);
}
}
消费者Service层
//name参数对应消费者名称
//fallback参数对应HelloService的实现类
@FeignClient(name = "eureka-provider", fallback = HelloServiceImpl.class)
public interface HelloService {
@RequestMapping("/hello")
public String hello(@RequestParam String name);
}
HelloService实现类
@Component
public class HelloServiceImpl implements HelloService {
//当Service层的hello方法失败时,调用此类中的同名方法
@Override
public String hello(@RequestParam String name) {
return "失败了--->" + name;
}
}