码迷,mamicode.com
首页 > 其他好文 > 详细

Feign (配合Hystrix)

时间:2020-06-19 19:19:32      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:失败   star   param   gns   ref   name   alt   准备   health   

由于spingcloud  版本更新比较快,此处重新整理一版:

 

版本:  Java 8 

   spring boot  <version>  2.1.15.RELEASE </version>

   <spring-cloud.version>Greenwich.SR6</spring-cloud.version>

 

1. Feign的使用(配合Hystrix)

准备:在 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 "上游服务异常";
    }
}

 

Feign (配合Hystrix)

标签:失败   star   param   gns   ref   name   alt   准备   health   

原文地址:https://www.cnblogs.com/lshan/p/13165194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!