Spring Cloud Netflix—声明性REST客户端:Feign

直接使用Ribbon API 您也能够直接使用LoadBalancerClient。例: public class MyClass { @Autowired private LoadBalancerClient loadBalancer;html

public void doStuff() {
    ServiceInstance instance = loadBalancer.choose("stores");
    URI storesUri = URI.create(String.format("http://%s:%s", instance.getHost(), instance.getPort()));
    // ... do something with the URI
}
复制代码

} 缓存Ribbon配置java

每一个Ribbon命名的客户端都有一个相应的子应用程序上下文,Spring Cloud维护,这个应用程序上下文在第一个请求中被延迟加载到命名的客户端。能够经过指定Ribbon客户端的名称,在启动时,能够更改此延迟加载行为,从而热切加载这些子应用程序上下文。spring

application.yml ribbon: eager-load: enabled: true clients: client1, client2, client3 声明性REST客户端:Feign Feign是一个声明式的Web服务客户端。这使得Web服务客户端的写入更加方便 要使用Feign建立一个界面并对其进行注释。它具备可插入注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。Spring Cloud增长了对Spring MVC注释的支持,并使用Spring Web中默认使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign时提供负载均衡的http客户端。json

如何加入Feign缓存

要在您的项目中包含Feign,请使用组org.springframework.cloud和工件ID spring-cloud-starter-feign的启动器。有关 使用当前的Spring Cloud发布列表设置构建系统的详细信息,请参阅Spring Cloud项目页面。服务器

示例spring boot应用app

@Configuration @ComponentScan @EnableAutoConfiguration @EnableEurekaClient @EnableFeignClients public class Application {负载均衡

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}
复制代码

} StoreClient.java @FeignClient("stores") public interface StoreClient { @RequestMapping(method = RequestMethod.GET, value = "/stores") List getStores();编码

@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
复制代码

} 在@FeignClient注释中,String值(以上“存储”)是一个任意的客户端名称,用于建立Ribbon负载平衡器(有关Ribbon支持的详细信息,请参阅下文))。您还能够使用url属性(绝对值或只是主机名)指定URL。应用程序上下文中的bean的名称是该接口的彻底限定名称。要指定您本身的别名值,您能够使用@FeignClient注释的qualifier值。url

以上的Ribbon客户端将会发现“商店”服务的物理地址。若是您的应用程序是Eureka客户端,那么它将解析Eureka服务注册表中的服务。若是您不想使用Eureka,您能够简单地配置外部配置中的服务器列表(例如,参见 上文)。

源码来源:http://minglisoft.cn/honghu/technology.html

相关文章
相关标签/搜索