共计 1510 个字符,预计需要花费 4 分钟才能阅读完成。
1、在 Feign 中用 Hystrix 实现服务调用容错
1.1、添加依赖和配置,并启用支持
1.1.1、添加依赖
<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、添加配置
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 的支持
@EnableFeignClients // 开启 Feign 支持 | |
@SpringBootApplication | |
public class HystrixSpringcloudApplication {public static void main(String[] args) {SpringApplication.run(HystrixSpringcloudApplication.class, args); | |
} | |
} |
1.2、添加 Feign 接口
public interface FeignClients { | |
public String hello(); | |
} |
1.3、添加 Controller
public class HelloController { | |
FeignClients feignClients; | |
"/hello") | (|
public String index(){return feignClients.hello();} | |
} |
1.4、实现回调类
public class HelloHstrix implements FeignClients { | |
public String hello() {return "出现错误!"; | |
} | |
} |
1.5、添加 fallback 属性
public interface FeignClients { | |
public String hello(); | |
} |
1.6、测试 fallbakc 状态
只开启 ” 服务中心 ”,访问 http://localhost:50007/hello,会提示错误。当把 ” 服务提供者 ” 也开启则会返回正确的数据。
正文完
星哥玩云-微信公众号
