1、在Feign中用Hystrix实现服务调用容错
1.1、添加依赖和配置,并启用支持
1.1.1、添加依赖
代码语言:javascript复制 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
1.1.2、添加配置
代码语言:javascript复制spring.application.name=hystrix
server.port=50007
eureka.client.fetch-registry=true
eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka01:50001/eureka/,http://eureka02:50002//eureka/
#开启支持
feign.hystrix.enabled=true
1.1.3、添加对Feign的支持
代码语言:javascript复制@EnableFeignClients //开启Feign支持
@SpringBootApplication
public class HystrixSpringcloudApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixSpringcloudApplication.class, args);
}
}
1.2、添加Feign接口
代码语言:javascript复制@FeignClient(name = "provider")
public interface FeignClients {
@GetMapping("/hello")
public String hello();
}
1.3、添加Controller
代码语言:javascript复制@RestController
public class HelloController {
@Autowired
FeignClients feignClients;
@GetMapping("/hello")
public String index(){
return feignClients.hello();
}
}
1.4、实现回调类
代码语言:javascript复制@Component
public class HelloHstrix implements FeignClients {
@Override
public String hello() {
return "出现错误!";
}
}
1.5、添加fallback属性
代码语言:javascript复制@FeignClient(name = "provider",fallback = HelloHstrix.class)
public interface FeignClients {
@GetMapping("/hello")
public String hello();
}
1.6、测试fallbakc状态
只开启"服务中心",访问http://localhost:50007/hello,会提示错误。当把"服务提供者"也开启则会返回正确的数据。