spring cloud笔记

来源:互联网 发布:摄像机ntp端口号 编辑:程序博客网 时间:2024/06/05 20:05

前言

前面学习到了使用Feign做负载均衡,并未设置到Feign的配置,本篇记录一下使用自定义配置去使用Feign

外部配置类

Spring Cloud Feign一个核心理念就是支持命名客户端。每个Feign客户端是组合组件的一部分,它们一起工作按需与远程服务器通信,并且开发人员可以使用@FeignClient注解调用客户端。Spring Cloud会根据ApplicationContext每个命名客户端的使用情况创建一个新的集合 FeignClientsConfiguration。这包含feign.Decodera feign.Encoder,feign.Contract等。

Spring Cloud可以通过声明额外的配置(在顶部指定FeignClientsConfiguration类)来使用Feign客户端@FeignClient。
代码和上一节的一样只是新建了配置的类

@FeignClient(name = "eureka-client",configuration = TestConfiguration.class)public interface ConfigClient {    @RequestMapping(method = RequestMethod.GET, value = "/")    String getValue(String info);}

通过configuration指明外部配置类
配置类的具体内容如下

public class TestConfiguration {    @Bean    public Contract feignContract() {        return new feign.Contract.Default();    }    @Bean    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {        return new BasicAuthRequestInterceptor("user", "password");    }}

使用feign.Contract代替SpringMvcContract,并配置一个基础的认证Interceptor.
Controller类没有什么变化,一样的即可进行测试.

通过手动配置

在某些情况下,可能需要以上述方法不可能自定义您的Feign客户端。在这种情况下,您可以使用Feign Builder API创建客户端 。具体如下

@Import(FeignClientsConfiguration.class)@RestControllerpublic class DefaultController {    private FeignClientService feignClientService;    public DefaultController(Decoder decoder, Encoder encoder, Client client){        this.feignClientService = Feign.builder().client(client)                .encoder(encoder)                .decoder(decoder)                .requestInterceptor(new BasicAuthRequestInterceptor("user","password"))                .target(FeignClientService.class,"http://eureka-client");    }    @RequestMapping(name = "/default",method = RequestMethod.GET)    public String  getInfo(){        return feignClientService.getValue("hello world!");    }}

通过构造函数可以配置一些信息,这里多数我们都可以自定义,也可以使用默认的配置.最终代理指定服务的客户端.

service

public interface FeignClientService {    @RequestLine("GET /")    String getValue(String info);}

@RequestLine声明请求的方式和url
更多的实例请参见github文档

测试

还是一样,通过访问 http://localhost:8083

依然会通过负载均衡分发到eureka的客户端.

结语

与君共勉!!

参考资料

spring cloud文档
github feign

案例源码

feign config

0 0