目录

前言:

  在asp.net core服务端处理关于响应压缩的请求,服务端的主要工作就是根据content-encoding头信息判断采用哪种方式压缩并返回。之前在群里有人问道过,现在的网络带宽这么高了还有必要在服务端针对请求进行压缩吗?确实,如今分布式和负载均衡技术这么成熟,很多需要处理高并发大数据的场景都可以通过增加服务器节点来进行。但是,在资源受限的情况下,或者是还没必要为了某一个点去增加新的服务器节点的时候,我们还是要采用一些程序本身的常规处理手段来进行处理。笔者个人认为响应压缩的使用场景是这样的,在带宽压力比较紧张的情况,且cpu资源比较充足的情况下,使用响应压缩整体效果还是比较明显的。
    有压缩就有解压,而解压的工作就是在请求客户端处理的。比如浏览器,这是我们最常用的http客户端,许多浏览器都是默认在我们发出请求的时候(比如我们浏览网页的时候)在request head中添加content-encoding,然后根据响应信息处理相关解压。这些都源于浏览器已经内置了关于请求压缩和解压的机制。类似的还有许多,比如常用的代理抓包工具filder也是内置这种机制的。只不过需要手动去处理,但实现方式都是一样的。有时候我们在自己写程序的过程中也需要使用这种机制,在传统的.net httpwebrequest类库中,并没有这种机制,后来版本中加入了httpclient,有自带的机制可以处理这种操作,

一、使用方式

首先我们来看一下直接在httpclient中如何处理响应压缩

//自定义httpclienthandler实例
httpclienthandler httpclienthandler = new httpclienthandler
{
    automaticdecompression = decompressionmethods.gzip
};
//使用传递自定义httpclienthandler实例的构造函数
using (httpclient client = new httpclient(httpclienthandler))
{
    var response = await client.getasync($"http://mydemo/home/getperson?userid={userid}");
}


这个操作还是非常简单的,我们操作的并不是httpclient的属性而是httpclienthandler中的属性,我们在之前的文章[.net core httpclient源码探究]中曾探讨过,httpclient的本质其实就是httpmessagehandler,而httpclient真正使用到的是httpmessagehandler最重要的一个子类httpclienthandler,所有的请求操作都是通过httpmessagehandler进行的。我们可以看到automaticdecompression接受的是decompressionmethods枚举,既然是枚举就说明包含了不止一个值,接下来我们查看decompressionmethods中的源码

[flags]
public enum decompressionmethods
{
    // 使用所有压缩解压缩算法。
    all = -1,
    // 不使用解压
    none = 0x0,
    // 使用gzip解压算法
    gzip = 0x1,
    // 使用deflate解压算法
    deflate = 0x2,
    // 使用brotli解压算法
    brotli = 0x4
}


该枚举默认都是针对常用输出解压算法,接下来我们看一下在httpclientfactory中如何处理响应压缩。在之前的文章[.net core httpclientfactory+consul实现服务发现]中我们曾探讨过httpclientfactory的大致工作方式默认primaryhandler传递的就是httpclienthandler实例,而且在我们注册httpclientfactory的时候是可以通过configureprimaryhttpmessagehandler自定义primaryhandler的默认值,接下来我们具体代码实现

services.addhttpclient("mydemo", c =>
{
    c.baseaddress = new uri("http://mydemo/");
}).configureprimaryhttpmessagehandler(provider=> new httpclienthandler
{
    automaticdecompression = decompressionmethods.gzip
});


其实在注册httpclientfactory的时候还可以使用自定义的httpclient,具体的使用方式是这样的

services.addhttpclient("mydemo", c =>
{
    c.baseaddress = new uri("http://mydemo/");
}).configurehttpclient(provider => new httpclient(new httpclienthandler
{
    automaticdecompression = decompressionmethods.gzip
}));


httpclient确实帮我们做了好多事情,只需要简单的配置一下就开启了针对响应压缩的处理。这更勾起了我们对httpclient的探讨,接下来我们就通过源码的方式查看它是如何发起可响应压缩请求,并解压响应结果的。

二、源码探究

通过上面的使用方式我们得知,无论使用哪种形式,最终都是针对httpclienthandler做配置操作,接下来我们查看httpclienthandler类中automaticdecompression属性的代码

public decompressionmethods automaticdecompression
{
    get => _underlyinghandler.automaticdecompression;
    set => _underlyinghandler.automaticdecompression = value;
}

它本身的值操作来自_underlyinghandler这个对象,也就是说读取和设置都是在操作_underlyinghandler.automaticdecompression,我们查找到_underlyinghandler对象的声明位置

private readonly socketshttphandler _underlyinghandler;

这里说明一下,httpclient的实质工作类是httpclienthandler,而httpclienthandler真正发起请求是依靠的socketshttphandler这个类,也就是说socketshttphandler是最原始发起请求的类。httpclienthandler本质还是通过socketshttphandler发起的http请求,接下来我们就查看socketshttphandler类是如何处理automaticdecompression这个属性的

public decompressionmethods automaticdecompression
{
    get => _settings._automaticdecompression;
    set
    {
        checkdisposedorstarted();
        _settings._automaticdecompression = value;
    }
}

这里的_settings不再是具体的功能类,而是用于初始化或者保存socketshttphandler的部分属性值的配置类

private readonly httpconnectionsettings _settings = new httpconnectionsettings();

这里我们不在分析socketshttphandler出处理响应压缩之外的其他代码,所以具体就不再看这些了,直接查找_settings._automaticdecompression属性引用的地方,最终找到了这段代码

if (settings._automaticdecompression != decompressionmethods.none)
{
    handler = new decompressionhandler(settings._automaticdecompression, handler);
}

这里就比较清晰了,真正处理请求响应压缩相关的都是在decompressionhandler中。正如我们之前所说的,httpclient真正的工作方式就是一些实现自httpmessagehandler的子类在工作,它把不同功能的实现模块都封装成了具体的handler中。当你需要使用哪个模块的功能,直接使用对应的handler操作类去发送处理请求即可。这种设计思路在asp.net core中体现的也是淋漓尽致,asp.net core采用的是构建不同终结点去处理和输出请求。通过这些我们可以得知decompressionhandler才是今天的主题,接下来我们就来查看decompressionhandler类的源码,我们先来看最核心的sendasync方法,这个方法是发送请求的执行方法

internal override async valuetask<httpresponsemessage> sendasync(httprequestmessage request, bool async, cancellationtoken cancellationtoken)
{
    //判断是否是gzip压缩请求,如果是则添加请求头accept-encoding头为gzip
    if (gzipenabled && !request.headers.acceptencoding.contains(s_gzipheadervalue))
    {
        request.headers.acceptencoding.add(s_gzipheadervalue);
    }
    //判断是否是deflate压缩请求,如果是则添加请求头accept-encoding头为deflate
    if (deflateenabled && !request.headers.acceptencoding.contains(s_deflateheadervalue))
    {
        request.headers.acceptencoding.add(s_deflateheadervalue);
    }
    //判断是否是brotli压缩请求,如果是则添加请求头accept-encoding头为brotli
    if (brotlienabled && !request.headers.acceptencoding.contains(s_brotliheadervalue))
    {
        request.headers.acceptencoding.add(s_brotliheadervalue);
    }
    //发送请求
    httpresponsemessage response = await _innerhandler.sendasync(request, async, cancellationtoken).configureawait(false);

    debug.assert(response.content != null);
    //获取返回的content-encoding输出头信息
    icollection<string> contentencodings = response.content.headers.contentencoding;
    if (contentencodings.count > 0)
    {
        string? last = null;
        //获取最后一个值
        foreach (string encoding in contentencodings)
        {
            last = encoding;
        }
        //根据响应头判断服务端采用的是否为gzip压缩
        if (gzipenabled && last == gzip)
        {
            //使用gzip解压算法解压返回内容,并从新赋值到response.content
            response.content = new gzipdecompressedcontent(response.content);
        }
        //根据响应头判断服务端采用的是否为deflate压缩
        else if (deflateenabled && last == deflate)
        {
            //使用deflate解压算法解压返回内容,并从新赋值到response.content
            response.content = new deflatedecompressedcontent(response.content);
        }
        //根据响应头判断服务端采用的是否为brotli压缩
        else if (brotlienabled && last == brotli)
        {
            //使用brotli解压算法解压返回内容,并从新赋值到response.content
            response.content = new brotlidecompressedcontent(response.content);
        }
    }
    return response;
}

通过上面的逻辑我们可以看到gzipenableddeflateenabledbrotlienabled三个bool类型的变量,中三个变量决定了采用哪种请求压缩方式,主要实现方式是

internal bool gzipenabled => (_decompressionmethods & decompressionmethods.gzip) != 0;
internal bool deflateenabled => (_decompressionmethods & decompressionmethods.deflate) != 0;
internal bool brotlienabled => (_decompressionmethods & decompressionmethods.brotli) != 0;

主要就是根据我们配置的decompressionmethods枚举值判断想获取哪种方式的压缩结果,解压的实现逻辑都封装在gzipdecompressedcontentdeflatedecompressedcontentbrotlidecompressedcontent中,我们看一下他们的具体的代码

private sealed class gzipdecompressedcontent : decompressedcontent
{
        public gzipdecompressedcontent(httpcontent originalcontent)
            : base(originalcontent)
        { }
        //使用gzipstream类对返回的流进行解压
        protected override stream getdecompressedstream(stream originalstream) =>
            new gzipstream(originalstream, compressionmode.decompress);
    }

    private sealed class deflatedecompressedcontent : decompressedcontent
    {
        public deflatedecompressedcontent(httpcontent originalcontent)
            : base(originalcontent)
        { }
        //使用deflatestream类对返回的流进行解压
        protected override stream getdecompressedstream(stream originalstream) =>
            new deflatestream(originalstream, compressionmode.decompress);
    }

    private sealed class brotlidecompressedcontent : decompressedcontent
    {
        public brotlidecompressedcontent(httpcontent originalcontent) :
            base(originalcontent)
        { }
        //使用brotlistream类对返回的流进行解压
        protected override stream getdecompressedstream(stream originalstream) =>
            new brotlistream(originalstream, compressionmode.decompress);
    }
}

其主要的工作方式就是使用对应压缩算法的解压方法得到原始信息。简单总结一下,httpclient关于压缩相关的处理机制是,首先根据你配置的decompressionmethods判断你想使用那种压缩算法。然后匹配到对应的压缩算法后添加accept-encoding请求头为你期望的压缩算法。最后根据响应结果获取content-encoding输出头信息,判断服务端采用的是哪种压缩算法,并采用对应的解压方法解压获取原始数据。

总结:

    通过本次探讨httpclient关于响应压缩的处理我们可以了解到,httpclient无论从设计上还是实现方式上都有非常高的灵活性和扩展性,这也是为什么到了.net core上官方只推荐使用httpclient一种http请求方式。由于使用比较简单,实现方式比较清晰,这里就不过多拗述。主要是是想告诉大家httpclient默认可以直接处理响应压缩,而不是和之前我们使用httpwebrequest的时候还需要手动编码的方式去实现。