SpringCloud RestClient Feign(章节5)

作者:jiangzz 电话:15652034180 微信:jiangzz_wx 微信公众账号:jiangzz_wy

Feign是一个声明性的Web服务客户端。它使编写Web服务客户端变得更容易。 Spring Cloud增加了对Spring MVC注释的支持,并使用了Spring Web中默认使用的相同HttpMessageConverters。 Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载均衡的http客户端。

快速入门

  • 引入依赖
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
  • FeignSpringBootApplication
@SpringBootApplication
@EnableFeignClients
public class FeignSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignSpringBootApplication.class,args);
    }
}
  • application.properties
eureka.client.register-with-eureka=false
eureka.client.healthcheck.enabled=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://jiangzz:123456@localhost:8761/eureka/
  • IUserServiceFeignClient
@FeignClient(name = "USER-SERVICE")
public interface IUserServiceFeignClient {
    @RequestMapping(value="/manager/user/{id}",method = {RequestMethod.GET})
    public User queyUserById(@PathVariable(value = "id") Integer id);
}
  • UserController
@RestController
public class UserController {
    @Autowired
    private IUserServiceFeignClient userServiceFeignClient;

    @RequestMapping(value = "/user/{id}",method={RequestMethod.GET})
    public User queryUserById(@PathVariable("id") Integer id){
       return  userServiceFeignClient.queyUserById(id);
    }
}

其中的IUserServiceFeignClient的name=USER-SERVICE属性指的是Feign会从eureka中查找命名服务,底层会更具接口方法的配置信息参数发送请求给远程的服务器这种实现比单纯的使用Ribbon更加的优雅。实际上Feign底层就是对Ribbon组件的封装。

Feigen 熔断

默认Feign没有开启熔断策略,需要用户在配置文件中指定

eureka.client.register-with-eureka=false
eureka.client.healthcheck.enabled=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://jiangzz:123456@localhost:8761/eureka/

feign.hystrix.enabled=true

修改IUserServiceFeignClient,添加failback属性

@FeignClient(name = "USER-SERVICE",fallback = UserServiceFailBack.class)
public interface IUserServiceFeignClient {
    @RequestMapping(value="/manager/user/{id}",method = {RequestMethod.GET})
    public User queyUserById(@PathVariable(value = "id") Integer id);
}

添加UserServiceFailBack实现服务降级

@Component
public class UserServiceFailBack implements IUserServiceFeignClient  {
    @Override
    public User queyUserById(Integer id) {
        return new User("测试用户",new Date(),true,1500.0);
    }
}

用户可以尝试将Feign引用的服务关闭,点击http://localhost:8080/user/1查看访问结果

{"id":null,"name":"测试用户","birthDay":"2019-05-30 07:38:21","sex":true,"salary":1500.0}

设置超时

配置application.proeprties设置对应服务的请求超时时间

eureka.client.register-with-eureka=false
eureka.client.healthcheck.enabled=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://jiangzz:123456@localhost:8761/eureka/

feign.client.config.USER-SERVICE.connect-timeout=500
feign.client.config.USER-SERVICE.read-timeout=500

feign.hystrix.enabled=true

当系统调用时如果超时,则会自动熔断

Hystrix Dashboard

配置pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</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-netflix-hystrix-dashboard</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
  • application.properties
eureka.client.register-with-eureka=false
eureka.client.healthcheck.enabled=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone=http://jiangzz:123456@localhost:8761/eureka/

feign.client.config.USER-SERVICE.connect-timeout=500
feign.client.config.USER-SERVICE.read-timeout=500
feign.hystrix.enabled=true

management.endpoints.web.exposure.include=*
  • FeignSpringBootApplication
@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard
@EnableCircuitBreaker
public class FeignSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignSpringBootApplication.class,args);
    }
}

配置HyStrix属性

在和Feign整合后,用户无法配置Feign的ComandProperties,但是可以通过配置Bean的形式配置

@SpringBootApplication
@EnableFeignClients
@EnableHystrixDashboard
@EnableCircuitBreaker
public class FeignSpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignSpringBootApplication.class,args);
    }

    @Bean
    public SetterFactory setterFactory(){
        SetterFactory setterFactory =new SetterFactory() {
            @Override
            public HystrixCommand.Setter create(Target<?> target, Method method) {

                String groupKey = target.name();
                String commandKey = Feign.configKey(target.type(), method);

                HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
                		//设置统计指标5秒为一个时间窗口
                        .withMetricsRollingStatisticalWindowInMilliseconds(5000)
                        //操过80%失败率
                        .withCircuitBreakerErrorThresholdPercentage(50)
                        //操作5个开启短路器
                        .withCircuitBreakerRequestVolumeThreshold(5)
                        //设置线程隔离
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                        //设置断路器的开启时间为5秒
                        .withCircuitBreakerSleepWindowInMilliseconds(5000);

                return HystrixCommand.Setter
                        .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
                        .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
                        .andCommandPropertiesDefaults(setter);
            }
        };
        return setterFactory;
    }
}

配合断路器查看工作效果!

更多精彩内容关注

微信公众账号

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值