spring cloud微服务实战 pdf_springcloud微服务架构开发实战:常见微服务的消费者

常见微服务的消费者

本节就常见的微服务的消费者进行介绍。在Java领域比较常用的消费者框架主要有HttpClient、Ribbon、Feign 等。

45a27f7edb1d6a0adf8ad8858e2374ae.png

Apache HttpClient

Apache HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP的客户端编程工具包,并且它支持HTTP最新的版本和建议。虽然在JDK的java.net包中已经提供了访问HTTP的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便了开发人员测试基于HTTP的接口,既提高了开发的效率,也方便提高代码的健壮性。

在之前章节的示例中,我们也大规模采用了HttpClient来作为REST客户端。

在程序中,我们经常使用RestTemplate实例来访问REST服务。RestTemplate 是Spring的核心类,用于同步客户端的HTTP访问。它简化了与HTTP服务器的通信,并强制执行RESTful原则。

默认情况下,RestTemplate 依赖于标准的JDK功能来建立HTTP连接,当然,我们也可以通过setRequestFactory属性来切换到使用不同的HTTP库,例如,上面我们所介绍的Apache HttpCli-ent, 以及其他的,如Netty、OkHtp等。

要使用Apache HttpClient,最方便的方式莫过于再添加Apache HttpClient依赖。

//依赖关系dependencies {//添加Apache HttpClient依赖compile ('org . apache . httpcomponents :httpclient:4.5.3')}

其次,通过RestTemplateBuilder来创建RestTemplate实例。

import org. spr ingframework .beans. factory .annotation . Autowired;import org. spr ingframework. boot . web. client. RestTemplateBuilder;import org. spr ingf r amework. context. annotation. Bean;import org. springframework . context . annotation . Configuration;import org. springfr amework . web. client.RestTemplate;@Configurationpublic class RestConfiguration {@Autowi redprivate RestTemplateBuilder builder;@Beanpublic RestTemplate restTemplate() {return builder .build() ;}}

最后,就能通过RestTemplate实例来访问RESTfulAPI服务了。

@Servicepublic class WeatherDataServiceImpl implements WeatherDataService {CAutowiredprivate RestTemplate restTemplate;private WeatherResponse doGetWeatherData (String uri) {ResponseEntity response = restTemplate . getForEntity (uri, String.class) ;//。。}// .。}
be80c0eacf3d0791aea5e8915dfc77b7.png

Ribbon

Spring Cloud Ribbon是基于Netlix Ribbon实现的一套客户端负载均衡的工具。它是一一个基于HTTP和TCP的客户端负载均衡器。

Ribbon的一一个中心概念就是命名客户端。每个负载平衡器都是组合整个服务组件的一部分,它们一起协作,并可以根据需要与远程服务器进行交互,获取包含命名客户端名称的集合。SpringCloud根据需要,使用RibbonClientConfiguration为每个命名客户端创建一个新的集合作为Applica-tionContext。这其中包括- - 个ILoadBalancer、一个RestClient和一个ServerListFilter。

Ribbon经常与Eureka结合使用。在典型的分布式部署中,Eureka 为所有微服务实例提供服务注册,而Ribbon则提供服务消费的客户端。Ribbon 客户端组件提供一- 系列完善的配置选项,如连接超时、重试、重试算法等。Ribbon内置可插拔、可定制的负载均衡组件。下 面是用到的一一些负载均衡策略:

●简单轮询负载均衡;

●加权响应时间负 载均衡;

●区域感知轮询负载均衡;

●随机负载均衡。

其中,区域感知负载均衡器是Ribbon 一个久经考验的功能,该负载均衡器会采取如下步骤。

●负载均衡器会检查、计算所有可用区域的状态。如果某个区域中平均每个服务器的活跃请求已经达到配置的阈值,该区域将从活跃服务器列表中排除。如果多于-一个区域已经到达阈值,平均每服务器拥有最多活跃请求的区域将被排除。

●最差的区域被排除后,从剩下的区域中,将按照服务器实例数的概率抽样法选择一 个区域。

●在选定区域中,将会根据给定负载均衡策略规则返回一个服务器。

在micro-weather-eureka-client应用基础上,我们稍作修改,使其成为一个新的应用mi-cro-weather-eureka-client-ribbon,作为本章节的示例。

1.所需环境

为了演示本例子,需要采用如下开发环境。

JDK 8。

Gradle 4.0。

● Redis 3.2.100。

● Spring Boot 2.0.0.M3。

●Spring Cloud Starter Netlix Eureka Client Finchley.M2。

●Spring Cloud Starter Netilix Ribbon。

2.项目配置

要使用Ribbon,最简单的方式莫过于添加Ribbon依赖。

//依赖关系dependencies {//添加Spring Cloud Starter Netflix Ribbon依赖compile (' org. spr ingframework. cloud: spring-cloud-starter-netflix-rib-bon')}

3.启用Ribbon

Spring Cloud提供了声明式@RibbonClient注解来使用Ribbon。

package com. waylau. spring. cloud. weather . config;import org. springframework.beans. factory . annotation. Autowired;import org. spr ingf r amework. boot. web. cl ient. RestTemplateBuilder;import org. springfr amework. cloud.client. loadbalancer .LoadBalanced;import org.spr ingframework .cloud. netflix. ribbon. RibbonCl ient;import org. spr ingfr amework. context. annotation. Bean;import org. springfr amework.context. annotation. Configuration;import org. springframework. web. client. RestTemplate;t REST配置类.* @since 1.0.0 2017年11月03日k Cauthor Way Lau@Configuration@RibbonClient (name = "ribbon-client", configuration = RibbonConfiguration.class)public class RestConfiguration {@Autowi redprivate RestTemplateBuilder builder;@Bean@LoadBalancedpublic RestTemplate restTemplate () {return builder .build() ;}}

其中RibbonConfiguration是Ribbon自定义的配置类,定义如下。

/ ***/package com. waylau. spring.cloud . weather . config;import org. spr ingframework.cloud.netflix. ribbon. ZonePreferenceServerListFilter;import org. springfr amework. context. annotation. Bean;import org. springframework. context. annotation. Configuration;import com. netflix. loadbalancer. IPing; import com. netflix. loadbalancer . PingUrl;/**城市配置.* @since 1.0.0 2017年11月3日 @author Way Lau@Configurationpublic class RibbonConfiguration {@Beanpublic ZonePreferenceServerListFilter serverListFilter() {ZonePreferenceServerListFilter filter = new ZonePreferenceServer-ListFilter ()filter .setZone ("myZone") ;return filter;@Beanpublic IPing ribbonPing() {return new PingUrl () ;}}

这样,我们就能通过应用名称msa-weather-city -eureka来访问微服务了,并且还实现了服务的负载均衡。

4.使用Ribbon

编写CityController,用于使用Ribbon配置的RestTemplate。

import org. springframework. beans. factory . annotation. Autowired;import org . springf ramework. web. bind. annotation. GetMapping;import org.spr ingframework . web. bind. annotation. RestController;import org. springf ramework. web. cl ient . RestTemplate;/**City Controller .* @since 1.0.0 2017年11月03日@author Way Lau@RestController public class CityController@Autowiredprivate RestTemplate res tTemplate;@GetMapping ("/cities")public String listCity() {//通过应用名称来查找String body = restTemplate . getForEntity ("http:/ /msa-weather-city-eureka/cities", String.class) .getBody() ;return body;}}

5.应用配置

该应用同时也是一个 Eureka Client。修改application.properties,将其修改为如下配置。

spring. application. name: micro-weather -eureka-client-ribbon eureka. client. serviceUrl .defaultZone: http://localhost:8761/eureka/

Feign

Feign是一- 个声明式的Web服务客户端,这使Web服务客户端的写人更加方便。它具有可插拔注解支持,包括Feign注解和JAX-RS注解。Feign 还支持可插拔编码器和解码器。Spring Cloud增加了对Spring MVC注解的支持,并且使用了在Spring Web中默认使用的相同的HttpMessageCon-verter。 在使用Feign时,Spring Cloud集成了Ribbon 和Eureka 来提供负载平衡的HTTP客户端。

在micro-weather-eureka-client应用基础上,我们稍作修改,使其成为一个新的应用mi-cro-weather- eureka-client-feign,作为本节的示例。

1.所需环境

为了演示本例子,需要采用如下开发环境。

●Gradle 4.0。

●Redis 3.2.100。

●Spring Boot 2.0.0.M3。

●Spring Cloud Starter Netflix Eureka Client Finchley.M2。

●Spring Cloud Starter OpenFeign Finchley.M2。

2.项目配置

为了使用Feign,增加如下配置。

dependencies {//添加Spring Cloud Starter OpenFeign依赖compile('org. spr ingframework. cloud:spring-cloud-starter-openfeign')}

3.启用Feign

要启用Feign,最简单的方式就是在应用的根目录的Application 类上添加org.springframework.cloud.netlix. feign.EnableFeignClients注解。

import org.springframework .boot. SpringApplication;import org. springfr amework . boot. autoconfigure . SpringBootApplication;import org. springframework. cloud. client . discovery . EnableDi scoveryClient;import org.springframework. cloud. netflix. feign. EnableFeignClients;/**★主应用程序.★asince 1.0.0 2017年11月04日* Cauthor Way Lau*/@SpringBootApplication@EnableDiscoveryCl ient@EnableFeignClientspublic class Appl ication {public static void main(String[] args) {SpringApplication. run (Application.class, args) ;}}

4.使用Feign

要使用Feign,首先是编写Feign请求接口。

package com. waylau. spring.cloud. weather .service;import org. spr ingf ramework. cloud . netflix. feign. FeignClient;import org. springfr amework. web . bind. annotation . GetMapping;★访问城市信息的客户端.* Gsince 1.0.0 2017年11月4日* @author Way Lau*/@FeignClient ("msa-weather-city-eureka")public interface CityClient {@GetMapping("/cities")String listCity() ;}}

其中,@FeignClient指定了要访问的服务的名称msa- weather-city-eureka。

在声明了CityClient 接口之后,我们就能在控制器CityController中使用该接口的实现。

import org. springframework .beans. factory .annotation. Autowired;import org. springframework. web .bind. annotation. GetMapping;import org. springf r amework. web.bind. annotation. RestController;import com. waylau. spring. cloud . weather . service. CityClient;/★** City Controller.★@since 1.0.0 2017年11月04日* @author Way Lau@RestControllerpublic class CityController {@Autowiredprivate CityClient cityClient;@GetMapping("/cities")public String listCity() {/通过Feign客户端来查找String body = cityClient. listCity() ;return body;}}

CityContoller 控制器专门用于请求获取城市信息的响应。这里,我们直接注入CityClient 接口即可,Feign框架会为我们提供具体的实现。

最后,修改application.properties。将其修改为如下配置。

spr ing . application. name: micro-weather -eureka-client-feign eureka. client. serviceUrl. defaultZone: http:/ /localhost: 8761/eureka/ feign.cl ient. config. feignName . connectTimeout: 5000feign. cl ient. config. feignName . readTimeout: 5000

其中:

● feign.client.config.feignName.connectTimeout为连接超时时间;

feign.client.conig. feignName.readTimeout为读数据的超时时间。

源码

本节示例所涉及的源码,见micro-weather-eureka-server、micro-weather-eureka-client 和msa-weather-city-eureka,以及micro-weather-eureka-client-ribbon和micro-weather- eureka-client-feign。

本篇文章内容给大家讲解的是常见微服务的消费者

  1. 下篇文章给大家讲解使用Feign实现服务的消费者;
  2. 觉得文章不错的朋友可以转发此文关注小编;
  3. 感谢大家的支持!
f9cf2dac6fceb047ba0cdb6366659288.png
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值