由于spingcloud 版本更新比较快,此处重新整理一版:
版本: Java 8
spring boot <version> 2.1.15.RELEASE </version>
<spring-cloud.version>Greenwich.SR6</spring-cloud.version>
准备:在 service MICRO-CLENT2-USER 写一个接口:
like:
@RequestMapping(value = "/hello/{word}",method = RequestMethod.GET) public String hello(@PathVariable("word") String word){ return feignService.hello(word); }
使用:
在service MICRO-CLENT2-USER 中使用Feign 调用 MICRO-CLENT1-USER 的接口
依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
主类:
@EnableDiscoveryClient @EnableFeignClients @EnableCircuitBreaker @SpringBootApplication public class EurekaServceApplication { public static void main(String[] args) { SpringApplication.run(EurekaServceApplication.class, args); } }
配置文件:
server: port: 9002 spring: application: name: MICRO-CLENT2-USER management: endpoint: health: #健康检测 查看 http://localhost:8761/actuator/health show-details: always eureka: client: service-url: defaultZone: http://root:root@127.0.0.1:8761/eureka/ instance: # 是否显示ip,如果不设置那么就会显示主机名,默认false prefer-ip-address: true feign: hystrix: enabled: true client: config: default: connectTimeout: 7000 readTimeout: 700
定义Feign调用接口:
/** @param: name :被调用服务的服务名 @param: configuration :Feign的配置,可以不配,建议配置,解决连接超时,retry @param: fallback :Feign 默认支持hystrix, 自定义一个类,然后实现方法即可,如果链路失败,自调用备胎,返回默认值(做异常提示) */ @FeignClient(name = "MICRO-CLENT1-USER",configuration = FeignConfig.class,fallback = FeignServiceHystrxFall.class) public interface FeignService { @RequestMapping(value = "/hello/{word}",method = RequestMethod.GET) public String hello(@PathVariable("word") String word); }
定义Feign 的Config
@Configuration public class FeignConfig {
//如果timeout 重试5次 @Bean public Retryer feignRetryer(){ return new Retryer.Default(60000,TimeUnit.SECONDS.toMillis(1),5); } }
@Component public class FeignServiceHystrxFall implements FeignService{ @Override public String hello(String word) { //调用服务异常,断路 //dosomething(); return "上游服务异常"; } }
关于hystrix 的相关配置:
hystrix: # === === === == 默认Command === === === == command: default: execution: isolation: # 调用隔离方式, 默认: 采用线程隔离, ExecutionIsolationStrategy:THREAD strategy: THREAD # 调用超时时间, 默认: 5 秒 thread: timeoutInMilliseconds: 8000 # 使用信号量隔离时, 命令调用最大的并发数 semaphore: maxConcurrentRequests: 10 #使用信号量隔离时, 命令fallback调用最大的并发数 fallback: isolation: semaphore: maxConcurrentRequests: 10 # === === === == 熔断器 === === === == circuitBreaker: # 熔断器在整个统计时间内是否开启的阀值, 默认20个请求 requestVolumeThreshold: 8 # 熔断器默认工作时间, 默认: 5 秒 sleepWindowInMilliseconds: 5 # 默认: 50%, 当出错率超过50% 后熔断器启动 errorThresholdPercentage: 50 # 是否强制开启熔断器阻断所有请求, 默认: false, 不开启 forceOpen: false # 是否允许熔断器忽略错误, 默认false, 不开启 forceClosed: false
原文:https://www.cnblogs.com/lshan/p/13165194.html