1.负载均衡Ribbon
1.1.Ribbon介绍
1.1.1.什么是Ribbon
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。Ribbon默认提供 很多种负载均衡策略,例如轮询、随机 等等。
1.1.2.负载均衡策略
负载均衡接口:com.netflix.loadbalancer.IRule
1.1.2.1.随机策略
com.netflix.loadbalancer.RandomRule
:该策略实现了从服务清单中随机选择一个服务实例的功能。
1.1.2.2.轮询策略
com.netflix.loadbalancer.RoundRobinRule
:该策略实现按照线性轮询的方式依次选择实例的功能。具体实现如下,在循环中增加了一个count计数变量,该变量会在每次轮询之后累加并求余服务总数
1.2.创建服务消费者
1.2.1.创建工程
springcloud_ribbon_consumer
1.2.2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>springcloud_ribbon_consumer</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-server客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.qf</groupId>
<artifactId>springcloud_common_pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
1.2.3.application.properties
spring.application.name=ribbon-consumer
#设置服务注册中心地址
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/
1.2.4.ConfigBean
package com.qf.config;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ConfigBean {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
//默认使用轮循的策略
//随机策略
@Bean
public RandomRule getRuleribbonRule() {
return new RandomRule();
}
}
1.2.5.controller
package com.qf.controller;
import com.qf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class UserController {
@Autowired
private RestTemplate restTemplate;
//从eureka注册中心获取服务端的ip、端口、要调用的服务
@Autowired
private LoadBalancerClient loadBalancerClient;
@RequestMapping(value = "consumer/user/{id}", method = RequestMethod.GET)
public User getUserBy(@PathVariable Integer id) {
ServiceInstance si = loadBalancerClient.choose("ribbon-provider");
//指定要调用的服务
String url = "http://" + si.getHost() + ":" + si.getPort() + "/user/" + id;
return restTemplate.getForObject(url, User.class);
}
}
1.2.6.App
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class);
}
}
1.3.创建两个服务提供者
1.3.1.创建工程
springcloud_ribbon_provider1,springcloud_ribbon_provider2
1.3.2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>springcloud_ribbon_provider1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-server客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.qf</groupId>
<artifactId>springcloud_common_pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>springcloud_ribbon_provider2</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-server客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.qf</groupId>
<artifactId>springcloud_common_pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
1.3.3.application.properties
#向注册中心注册的名字
spring.application.name=ribbon-provider
server.port=9090
#设置注册中心的地址
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/
#向注册中心注册的名字
spring.application.name=ribbon-provider
server.port=9091
#设置注册中心的地址
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/
1.3.4.service
package com.qf.service;
import com.qf.pojo.User;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUser(Integer id) {
return new User(id,"王粪堆-provider1",11);
}
}
package com.qf.service;
import com.qf.pojo.User;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUser(Integer id) {
return new User(id,"王粪堆-provider2",22);
}
}
1.3.5.controller
package com.qf.controller;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
@Autowired
private UserService userService;
@RequestMapping("user/{id}")
public User getUser(@PathVariable Integer id){
return userService.getUser(id);
}
}
package com.qf.controller;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
@Autowired
private UserService userService;
@RequestMapping("user/{id}")
public User getUser(@PathVariable Integer id){
return userService.getUser(id);
}
}
1.2.6.App
package com.qf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient//允许向服务端注册服务
@SpringBootApplication
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class, args);
}
}
package com.qf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient//允许向服务端注册服务
@SpringBootApplication
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class, args);
}
}
1.4.测试
分别使用轮询和随机策略调用服务提供者
2.声明式服务调用Feign
2.1.背景
当我们通过RestTemplate调用其它服务的API时,所需要的参数须在请求的URL中进行拼接,如果参数少的话或许我们还可以忍受,一旦有多个参数的话,这时拼接请求字符串就会效率低下,并且显得好傻。
并且ribbon没有剔除掉死亡的服务节点。
那么有没有更好的解决方案呢?答案是确定的有,Netflix已经为我们提供了一个框架:Feign。
2.2.Feign概述
Feign是Netflix开发的声明式的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。
Spring Cloud集成Feign并对其进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和支持Eureka,从而让Feign的使用更加方便。
2.3.Feign入门
2.3.1.创建feign接口工程
2.3.2.1.创建工程
springcloud_feign_api
2.3.1.2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>springcloud_feign_api</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--Spring Cloud OpenFeign Starter -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.qf</groupId>
<artifactId>springcloud_common_pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.3.1.3.feign
package com.qf.feign;
import com.qf.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//获取eureka-provider的调用地址,且具有负载均衡的能力
@FeignClient(value="feign-provider")
public interface UserFeign {
@RequestMapping(value="/user")
public User getUser();
}
2.3.2.创建服务消费者
2.3.2.1.创建工程
springcloud_feign_consumer
2.3.2.2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>springcloud_feign_consumer</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-server客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.qf</groupId>
<artifactId>springcloud_feign_api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.3.2.3.application.properties
#设置注册到eureka的名字
spring.application.name=feign-consumer
#端口
server.port=8666
#注册中心的地址
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
2.3.2.3.Controller
package com.qf.controller;
import com.qf.feign.UserFeign;
import com.qf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserFeign userFeign;
@RequestMapping("/consumer/user")
public User getUser(){
return userFeign.getUser();
}
}
2.3.2.4.App
package com.qf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients//开启feign接口扫描
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class, args);
}
}
2.3.3.创建服务提供者
2.3.3.1.创建工程
springcloud_feign_provider
2.3.3.2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>springcloud_feign_provider</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--eureka-server客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.qf</groupId>
<artifactId>springcloud_common_pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.3.3.3.application.properties
#向注册中心注册的名字
spring.application.name=feign-provider
server.port=9090
#设置注册中心的地址
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka/
2.3.3.3.Controller
package com.qf.controller;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
@Autowired
private UserService userService;
@RequestMapping("/provider/user")
public User getUser(){
return userService.getUser();
}
}
2.3.3.4.service
import com.qf.pojo.User;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUser() {
return new User(1,"王粪堆-provider1",11);
}
}
2.3.3.4.App
package com.qf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient
@SpringBootApplication
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class, args);
}
}
2.3.4.测试
2.4.Feign原理
2.4.1.将Feign接口注入到Spring容器中
@EnableFeignClients注解开启Feign扫描,先调用FeignClientsRegistrar.registerFeignClients()方法扫描@FeignClient注解的接口,再将这些接口注入到Spring IOC容器中,方便后续被调用。
public void registerFeignClients(AnnotationMetadata metadata,
BeanDefinitionRegistry registry) {
... ... ...
//扫描feign接口
for (String basePackage : basePackages) {
Set<BeanDefinition> candidateComponents = scanner
.findCandidateComponents(basePackage);
for (BeanDefinition candidateComponent : candidateComponents) {
if (candidateComponent instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition)
candidateComponent;
//获得UserFeign的详细信息
AnnotationMetadata annotationMetadata = beanDefinition.getMetadata();
Assert.isTrue(annotationMetadata.isInterface(),
"@FeignClient can only be specified on an interface");
Map<String, Object> attributes = annotationMetadata
.getAnnotationAttributes(FeignClient.class.getCanonicalName());
String name = getClientName(attributes);
registerClientConfiguration(registry, name,
attributes.get("configuration"));
//注入Feign接口到Spring容器中
registerFeignClient(registry, annotationMetadata, attributes);
}
}
}
}
2.4.2.RequestTemplate封装请求信息
SynchronousMethodHandler.invoke():
当定义的的Feign接口中的方法被调用时,通过JDK的代理方式为Feign接口生成了一个动态代理类,当生成代理时,Feign会为每个接口方法创建一个RequestTemplate。该对象封装了HTTP请求需要的全部信息,如请url、参数,请求方式等信息都是在这个过程中确定的。
public Object invoke(Object[] argv) throws Throwable {
//创建一个RequestTemplate
RequestTemplate template = this.buildTemplateFromArgs.create(argv);
Retryer retryer = this.retryer.clone();
while(true) {
try {
//发出请求
return this.executeAndDecode(template);
} catch (RetryableException var8) {
... ... ...
}
}
}
package feign;
public final class RequestTemplate implements Serializable {
... ... ... ... ... ...
private UriTemplate uriTemplate;
private HttpMethod method;
private Body body;
... ... ... ... ... ...
}
2.4.3.发起请求
SynchronousMethodHandler.executeAndDecode():
通过RequestTemplate生成Request,然后把Request交给Client去处理,Client可以是JDK原生的URLConnection,Apache的HttpClient,也可以是OKhttp,最后Client结合Ribbon负载均衡发起服务调用。
Object executeAndDecode(RequestTemplate template) throws Throwable {
//生成请求对象
Request request = this.targetRequest(template);
if (this.logLevel != Level.NONE) {
this.logger.logRequest(this.metadata.configKey(), this.logLevel, request);
}
long start = System.nanoTime();
Response response;
try {
//发起请求
response = this.client.execute(request, this.options);
} catch (IOException var15) {
... ... ...
throw FeignException.errorExecuting(request, var15);
}
}
2.5.Feign参数传递
传参方式:
- restful风格:
feign接口:@PathVarible【拼接restful形式的url】
- ?传参
feign接口:@RequestParam【拼接?形式的url】
- pojo参数
provider: @RequestBody User user【获取请求体中的json串】
2.6.Feign请求超时
2.6.1.模拟超时
修改
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUser() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new User(1,"王粪堆",18);
}
}
测试:
2.6.2.设置feign超时时间
#全局配置
# 请求连接的超时时间
ribbon.ConnectTimeout=6000
# 请求处理的超时时间
ribbon.ReadTimeout=6000
2.6.3.测试
1.测试超时
略... ... ... ... ... ...
2.7.剔除死亡的服务节点
2.7.1.模拟服务节点死亡你
- 创建springcloud_feign_provider2,并启动
- 关闭springcloud_feign_provider2
- 观察是否剔除死亡的服务节点
2.7.2.设置剔除死亡的服务节点
微服务的负载均衡策略会剔除死亡的服务节点:
# 对所有操作请求都进行重试
ribbon.OkToRetryOnAllOperations=true
# 对当前实例的重试次数
ribbon.MaxAutoRetries=0
# 切换实例的重试次数
ribbon.MaxAutoRetriesNextServer=1
2.7.Feign性能优化
2.7.1.Gzip压缩
2.7.1.1 gzip 介绍
-
gzip 介绍:gzip 是一种数据格式,采用用 deflate 算法压缩 data;gzip 是一种流行的文件压缩算法,应用十分广泛,尤其是在 Linux 平台。
-
gzip 能力:当 Gzip 压缩到一个纯文本文件时,效果是非常明显的,大约可以减少 70%以上的文件大小。
-
gzip 作用:网络数据经过压缩后实际上降低了网络传输的字节数,最明显的好处就是可以加快网页加载的速度。网页加载速度加快的好处不言而喻,除了节省流量,改善用户的浏览体验外,另一个潜在的好处是 Gzip 与搜索引擎的抓取工具有着更好的关系。例如 Google就可以通过直接读取 gzip 文件来比普通抓取 更快地检索网页。
2.7.1.2.HTTP压缩传输规定
**第一:**客户端向服务器请求中带有:Accept-Encoding:gzip,
deflate 字段,向服务器表示,客户端支持的压缩格式(gzip 或者 deflate),如果不发送该消息头,服务器是不会压缩的。
**第二:**服务端在收到请求之后,如果发现请求头中含有 Accept-Encoding 字段,并且支持该类型的压缩,就对响应报文压缩之后返回给客户端,并且携带 Content-Encoding:gzip 消息头,表示响应报文是根据该格式压缩过的。
**第三:**客户端接收到请求之后,先判断是否有
Content-Encoding 消息头,如果有,按该格式解压报文。否则按正常报文处理。
2.7.1.2.Gzip压缩案例
2.7.1.2.1.创建工程
springcloud_feign_consumer_gzip,拷贝springcloud_feign_consumer
2.7.1.2.2.application.properties
1、设置Feign到Provider 的请求与相应的Gzip
#-----------------------------feign gzip
#配置请求 GZIP 压缩
feign.compression.request.enabled=true
#配置响应 GZIP 压缩
feign.compression.response.enabled=true
#配置压缩支持的 MIME TYPE
feign.compression.request.mime-types= text/xml,application/xml,application/json
#配置压缩数据大小的最小阀值,默认 2048
feign.compression.request.min-request-size=512
2、对客户端浏览器的请求以及 Consumer对 provider 的做 Gzip 压缩
#-----------------------------spring cloud gzip
#是否启用压缩
server.compression.enabled=true
#配置压缩支持的 MIME TYPE,***可省略***
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain
注意:只配置 Consumer
2.7.1.2.3.测试
2.7.2.Http连接池
2.7.2.1.http的背景原理
Http连接需要的 3 次握手 4 次分手开销很大,涉及到多个数据包的交换,并且也很耗时间,这一开销对于大量的比较小的 http 消息来说更大。
2.7.2.2.优化解决方案
a. 如果我们直接采用 http 连接池,节约了大量的 3 次握手 4 次分手;这样能大大提升吞吐率。
b. feign 的 http 客户端支持 3 种框架;HttpURLConnection、httpclient、okhttp;默认HttpURLConnection。
c. 传统的 HttpURLConnection 是 JDK 自带的,并不支持连接池,如果要实现连接池的机制,还需要自己来管理连
接对象。
d. HttpClient 相比传统 JDK 自带的HttpURLConnection,它封装了访问 http 的请求头,参数,内容体,响应等;
它不仅使客户端发送 HTTP 请求变得容易,而且也方便了开发人员测试接口(基于 Http 协议的),即提高了开
发的效率,也方便提高代码的健壮性;另外高并发大量的请求网络的时候,还是用“连接池”提升吞吐量。
2.7.2.3.Http连接池案例
2.7.2.3.1.创建工程
springcloud_feign_consumer_httpclient,拷贝springcloud_feign_consumer
2.7.2.3.2.pom.xml
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2.7.1.2.3.application.properties
#启用httpclient ***可省略***
feign.httpclient.enabled=true