Spring Cloud Feign 声明式服务调用

Spring Cloud Feign 声明式服务调用

基于Netfix Feign 实现的,其整合了 Spring Cloud Ribbon 与 Spring Cloud Hystrix 组件,并且提供了一种声明式的Web服务客户端定义方式。

简单使用

  • 创建新项目feign-consumer
  • pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency><dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>
    
  • 主类注释:

    @EnableFeignClients
    @EnableDiscoveryClient
    @SpringBootApplication
    public class FeignConsumerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(FeignConsumerApplication.class, args);
        }
    }
    
  • Hello-service:

    @FeignClient("hello-service")
    public interface HelloService {
        @RequestMapping("/hello")
        String hello();
    }
    
  • ConsumerController :

    @RestController
    public class ConsumerController {
        @Autowired
        HelloService helloService;
    
        @RequestMapping(value = "/feign-consumer",method = RequestMethod.GET)
        public String helloConsumer(){
            return helloService.hello();
        }
    }
    
  • 配置文件:

    spring.application.name=feign-consumer
    server.port=9001
    
    eureka.client.service-url.defaultZone=http://localhost:1111/eureka/ 
    

到这里已经完成了,接下来就是想ribbon那样使用了,http://localhost:9001/feign-consumer 就可以访问到helloWorld了

参数绑定

feign可以调用服务接口,可传递的参数有好几种:

例子:

String hello(@RequestParam(“name”) String name);
String hello(@RequestParam(“name”) String name,@RequestParam(“age”) Integer age);
String hello (@RequestBody User user);

这个就简单说明下就可以了

继承特性

这个是将接口定义从Controller中剥离出来使用的,有需要做接口定义共享才有用,这里略过╮(╯_╰)╭

Ribbon配置

对于Ribbon的属性在feign里都是可以使用的

全局配置:

ribbon.<key>=<value>

指定服务配置[与ribbon一样的]:

<client>.ribbon.key=value

Hystrix配置

配置:

hystrix.command.default.<key> = <value>
e.g.:hystrix.command.default.isolation.thread.timeoutInMilliseconds = 5000

feign.hystrix.enabled = false #关闭Hystrix功能
hystrix.command.default.execution.timeout.enabled=false  #关闭熔断功能

非全局关闭Hystrix功能:

方法级别使用:
@Configuration
Public class DisableHtstrixConfiguration{
    @Bean
    @Scop("prototype")
    public Feign.Builder feignBuilder(){
        return Feign.builder();
    }
}
在HelloService 的 @FeignClient注解工作configuration参数引入↑面配置
@FeignClient(name="HELLO-SERVICE",configuration = DisableHtstrixConfiguration.class)
public interface HelloService(...)

指令配置

hystrix.command.<commandKey>....=<value>

服务降级配置

e.g.:
@Component
public class HelloServiceFallback implements HelloService{

    @Override
    public String hello() {
        return "error";
    }
}

@FeignClient(name="hello-service",fallback = HelloServiceFallback.class)
public interface HelloService {
    @RequestMapping("/hello")
    String hello();
}

多了一个降级的接口实现类。作为降级是的调用。

其他配置

请求压缩【不考虑,碰到再说,这边的版本很低】

日志配置:

开启DEBUG日志:

logging.level.com.didispace.web.HelloService=DEBUG
#由于Feign客户端默认等级问MOME,不会有Feign调用过程中的信息。SO:主类加点东东↓
包:import feign.Logger;
依赖:
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-logging</artifactId>
        </dependency>
主类:
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }

亲测没什么效果╮(╯_╰)╭
就打印了下面的东东 而且就打印了一次

2018-02-26 18:10:23.187  INFO 17504 --- [hello-service-1] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1cdd34b3: startup date [Mon Feb 26 18:10:23 CST 2018]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@77409d64
2018-02-26 18:10:23.222  INFO 17504 --- [hello-service-1] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-02-26 18:10:23.330  INFO 17504 --- [hello-service-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: hello-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-02-26 18:10:23.352  INFO 17504 --- [hello-service-1] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-hello-service
2018-02-26 18:10:23.367  INFO 17504 --- [hello-service-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client:hello-service instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=hello-service,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2018-02-26 18:10:23.370  INFO 17504 --- [hello-service-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2018-02-26 18:10:23.423  INFO 17504 --- [hello-service-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: hello-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-02-26 18:10:23.425  INFO 17504 --- [hello-service-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client hello-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=hello-service,current list of Servers=[windows10.microdone.cn:1234],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;    Instance count:1;    Active connections count: 0;    Circuit breaker tripped count: 0;    Active connections per server: 0.0;]
},Server stats: [[Server:windows10.microdone.cn:1234;    Zone:defaultZone;    Total Requests:0;    Successive connection failure:0;    Total blackout seconds:0;    Last connection made:Thu Jan 01 08:00:00 CST 1970;    First connection made: Thu Jan 01 08:00:00 CST 1970;    Active Connections:0;    total failure count in last (1000) msecs:0;    average resp time:0.0;    90 percentile resp time:0.0;    95 percentile resp time:0.0;    min resp time:0.0;    max resp time:0.0;    stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@6b678d4b
2018-02-26 18:10:24.372  INFO 17504 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: hello-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647

2018-02-27
小杭

    原文作者:Spring Cloud
    原文地址: https://blog.csdn.net/xiaohangblog/article/details/79389885
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞