You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

564 lines
74 KiB

4 months ago
<!DOCTYPE HTML>
<html lang="zh-CN" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>解析数据帧 - Rust语言圣经(Rust Course)</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<link rel="stylesheet" href="../theme/style.css">
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item affix "><a href="../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../some-thoughts.html">Datav: 可编程的数据可视化平台和可观测性平台</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div></div></a></li><li><ol class="section"><li class="chapter-item "><a href="../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></li></ol></li><li class="chapter-item "><a href="../basic/flow-control.html"><strong aria-hidden="true">2.5.</strong> 流程控制</a></li><li class="cha
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/sunface/rust-course/edit/main/src/advance-practice/frame.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<!-- Page table of contents -->
<div class="sidetoc"><nav class="pagetoc"></nav></div>
<main>
<h1 id="解析数据帧"><a class="header" href="#解析数据帧">解析数据帧</a></h1>
<p>现在,鉴于大家已经掌握了 Tokio 的基本 I/O 用法,我们可以开始实现 <code>mini-redis</code> 的帧 <code>frame</code>。通过帧可以将字节流转换成帧组成的流。每个帧就是一个数据单元,例如客户端发送的一次请求就是一个帧。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use bytes::Bytes;
enum Frame {
Simple(String),
Error(String),
Integer(u64),
Bulk(Bytes),
Null,
Array(Vec&lt;Frame&gt;),
}
<span class="boring">}</span></code></pre></pre>
<p>可以看到帧除了数据之外,并不具备任何语义。命令解析和实现会在更高的层次进行(相比帧解析层)。我们再来通过 HTTP 的帧来帮大家加深下相关的理解:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>enum HttpFrame {
RequestHead {
method: Method,
uri: Uri,
version: Version,
headers: HeaderMap,
},
ResponseHead {
status: StatusCode,
version: Version,
headers: HeaderMap,
},
BodyChunk {
chunk: Bytes,
},
}
<span class="boring">}</span></code></pre></pre>
<p>为了实现 <code>mini-redis</code> 的帧,我们需要一个 <code>Connection</code> 结构体,里面包含了一个 <code>TcpStream</code> 以及对帧进行读写的方法:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::net::TcpStream;
use mini_redis::{Frame, Result};
struct Connection {
stream: TcpStream,
// ... 这里定义其它字段
}
impl Connection {
/// 从连接读取一个帧
///
/// 如果遇到EOF则返回 None
pub async fn read_frame(&amp;mut self)
-&gt; Result&lt;Option&lt;Frame&gt;&gt;
{
// 具体实现
}
/// 将帧写入到连接中
pub async fn write_frame(&amp;mut self, frame: &amp;Frame)
-&gt; Result&lt;()&gt;
{
// 具体实现
}
}
<span class="boring">}</span></code></pre></pre>
<p>关于 Redis 协议的说明,可以看看<a href="https://redis.io/topics/protocol">官方文档</a><code>Connection</code> 代码的完整实现见<a href="https://github.com/tokio-rs/mini-redis/blob/tutorial/src/connection.rs">这里</a>.</p>
<h2 id="缓冲读取buffered-reads"><a class="header" href="#缓冲读取buffered-reads">缓冲读取(Buffered Reads)</a></h2>
<p><code>read_frame</code> 方法会等到一个完整的帧都读取完毕后才返回,与之相比,它底层调用的<code>TcpStream::read</code> 只会返回任意多的数据(填满传入的缓冲区 buffer ),它可能返回帧的一部分、一个帧、多个帧,总之这种读取行为是不确定的。</p>
<p><code>read_frame</code> 的底层调用 <code>TcpStream::read</code> 读取到部分帧时,会将数据先缓冲起来,接着继续等待并读取数据。如果读到多个帧,那第一个帧会被返回,然后剩下的数据依然被缓冲起来,等待下一次 <code>read_frame</code> 被调用。</p>
<p>为了实现这种功能,我们需要为 <code>Connection</code> 增加一个读取缓冲区。数据首先从 <code>socket</code> 中读取到缓冲区中,接着这些数据会被解析为帧,当一个帧被解析后,该帧对应的数据会从缓冲区被移除。</p>
<p>这里使用 <a href="https://docs.rs/bytes/1/bytes/struct.BytesMut.html"><code>BytesMut</code></a> 作为缓冲区类型,它是 <a href="https://docs.rs/bytes/1/bytes/struct.Bytes.html"><code>Bytes</code></a> 的可变版本。</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use bytes::BytesMut;
use tokio::net::TcpStream;
pub struct Connection {
stream: TcpStream,
buffer: BytesMut,
}
impl Connection {
pub fn new(stream: TcpStream) -&gt; Connection {
Connection {
stream,
// 分配一个缓冲区具有4kb的缓冲长度
buffer: BytesMut::with_capacity(4096),
}
}
}
<span class="boring">}</span></code></pre></pre>
<p>接下来,实现 <code>read_frame</code> 方法:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::io::AsyncReadExt;
use bytes::Buf;
use mini_redis::Result;
pub async fn read_frame(&amp;mut self)
-&gt; Result&lt;Option&lt;Frame&gt;&gt;
{
loop {
// 尝试从缓冲区的数据中解析出一个数据帧,
// 只有当数据足够被解析时,才返回对应的帧
if let Some(frame) = self.parse_frame()? {
return Ok(Some(frame));
}
// 如果缓冲区中的数据还不足以被解析为一个数据帧,
// 那么我们需要从 socket 中读取更多的数据
//
// 读取成功时会返回读取到的字节数0 代表着读到了数据流的末尾
if 0 == self.stream.read_buf(&amp;mut self.buffer).await? {
// 代码能执行到这里,说明了对端关闭了连接,
// 需要看看缓冲区是否还有数据,若没有数据,说明所有数据成功被处理,
// 若还有数据,说明对端在发送帧的过程中断开了连接,导致只发送了部分数据
if self.buffer.is_empty() {
return Ok(None);
} else {
return Err(&quot;connection reset by peer&quot;.into());
}
}
}
}
<span class="boring">}</span></code></pre></pre>
<p><code>read_frame</code> 内部使用循环的方式读取数据,直到一个完整的帧被读取到时,才会返回。当然,当远程的对端关闭了连接后,也会返回。</p>
<h4 id="buf-特征"><a class="header" href="#buf-特征"><code>Buf</code> 特征</a></h4>
<p>在上面的 <code>read_frame</code> 方法中,我们使用了 <code>read_buf</code> 来读取 socket 中的数据,该方法的参数是来自 <a href="https://docs.rs/bytes/"><code>bytes</code></a> 包的 <code>BufMut</code></p>
<p>可以先来考虑下该如何使用 <code>read()</code><code>Vec&lt;u8&gt;</code> 来实现同样的功能 :</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::net::TcpStream;
pub struct Connection {
stream: TcpStream,
buffer: Vec&lt;u8&gt;,
cursor: usize,
}
impl Connection {
pub fn new(stream: TcpStream) -&gt; Connection {
Connection {
stream,
// 4kb 大小的缓冲区
buffer: vec![0; 4096],
cursor: 0,
}
}
}
<span class="boring">}</span></code></pre></pre>
<p>下面是相应的 <code>read_frame</code> 方法:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use mini_redis::{Frame, Result};
pub async fn read_frame(&amp;mut self)
-&gt; Result&lt;Option&lt;Frame&gt;&gt;
{
loop {
if let Some(frame) = self.parse_frame()? {
return Ok(Some(frame));
}
// 确保缓冲区长度足够
if self.buffer.len() == self.cursor {
// 若不够,需要增加缓冲区长度
self.buffer.resize(self.cursor * 2, 0);
}
// 从游标位置开始将数据读入缓冲区
let n = self.stream.read(
&amp;mut self.buffer[self.cursor..]).await?;
if 0 == n {
if self.cursor == 0 {
return Ok(None);
} else {
return Err(&quot;connection reset by peer&quot;.into());
}
} else {
// 更新游标位置
self.cursor += n;
}
}
}
<span class="boring">}</span></code></pre></pre>
<p>在这段代码中,我们使用了非常重要的技术:通过游标( cursor )跟踪已经读取的数据,并将下次读取的数据写入到游标之后的缓冲区中,只有这样才不会让新读取的数据将之前读取的数据覆盖掉。</p>
<p>一旦缓冲区满了,还需要增加缓冲区的长度,这样才能继续写入数据。还有一点值得注意,在 <code>parse_frame</code> 方法的内部实现中,也需要通过游标来解析数据: <code>self.buffer[..self.cursor]</code>,通过这种方式,我们可以准确获取到目前已经读取的全部数据。</p>
<p>在网络编程中,通过字节数组和游标的方式读取数据是非常普遍的,因此 <code>bytes</code> 包提供了一个 <code>Buf</code> 特征,如果一个类型可以被读取数据,那么该类型需要实现 <code>Buf</code> 特征。与之对应,当一个类型可以被写入数据时,它需要实现 <code>BufMut</code></p>
<p><code>T: BufMut</code> ( 特征约束,说明类型 <code>T</code> 实现了 <code>BufMut</code> 特征 ) 被传给 <code>read_buf()</code> 方法时,缓冲区 <code>T</code> 的内部游标会自动进行更新。正因为如此,在使用了 <code>BufMut</code> 版本的 <code>read_frame</code> 中,我们并不需要管理自己的游标。</p>
<p>除了游标之外,<code>Vec&lt;u8&gt;</code> 的使用也值得关注,该缓冲区在使用时必须要被初始化: <code>vec![0; 4096]</code>,该初始化会创建一个 4096 字节长度的数组,然后将数组的每个元素都填充上 0 。当缓冲区长度不足时,新创建的缓冲区数组依然会使用 0 被重新填充一遍。 事实上,这种初始化过程会存在一定的性能开销。</p>
<p><code>Vec&lt;u8&gt;</code> 相反, <code>BytesMut</code><code>BufMut</code> 就没有这个问题,它们无需被初始化,而且 <code>BytesMut</code> 还会阻止我们读取未初始化的内存。</p>
<h2 id="帧解析"><a class="header" href="#帧解析">帧解析</a></h2>
<p>在理解了该如何读取数据后, 再来看看该如何通过两个部分解析出一个帧:</p>
<ul>
<li>确保有一个完整的帧已经被写入了缓冲区,找到该帧的最后一个字节所在的位置</li>
<li>解析帧</li>
</ul>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use mini_redis::{Frame, Result};
use mini_redis::frame::Error::Incomplete;
use bytes::Buf;
use std::io::Cursor;
fn parse_frame(&amp;mut self)
-&gt; Result&lt;Option&lt;Frame&gt;&gt;
{
// 创建 `T: Buf` 类型
let mut buf = Cursor::new(&amp;self.buffer[..]);
// 检查是否读取了足够解析出一个帧的数据
match Frame::check(&amp;mut buf) {
Ok(_) =&gt; {
// 获取组成该帧的字节数
let len = buf.position() as usize;
// 在解析开始之前,重置内部的游标位置
buf.set_position(0);
// 解析帧
let frame = Frame::parse(&amp;mut buf)?;
// 解析完成,将缓冲区该帧的数据移除
self.buffer.advance(len);
// 返回解析出的帧
Ok(Some(frame))
}
// 缓冲区的数据不足以解析出一个完整的帧
Err(Incomplete) =&gt; Ok(None),
// 遇到一个错误
Err(e) =&gt; Err(e.into()),
}
}
<span class="boring">}</span></code></pre></pre>
<p>完整的 <code>Frame::check</code> 函数实现在<a href="https://github.com/tokio-rs/mini-redis/blob/tutorial/src/frame.rs#L63-L100">这里</a>,感兴趣的同学可以看看,在这里我们不会对它进行完整的介绍。</p>
<p>值得一提的是, <code>Frame::check</code> 使用了 <code>Buf</code> 的字节迭代风格的 API。例如为了解析一个帧首先需要检查它的第一个字节该字节用于说明帧的类型。这种首字节检查是通过 <code>Buf::get_u8</code> 函数完成的,该函数会获取游标所在位置的字节,然后将游标位置向右移动一个字节。</p>
<h2 id="缓冲写入buffered-writes"><a class="header" href="#缓冲写入buffered-writes">缓冲写入(Buffered writes)</a></h2>
<p>关于帧操作的另一个 API 是 <code>write_frame(frame)</code> 函数,它会将一个完整的帧写入到 socket 中。 每一次写入,都会触发一次或数次系统调用,当程序中有大量的连接和写入时,系统调用的开销将变得非常高昂,具体可以看看 SyllaDB 团队写过的一篇<a href="https://www.scylladb.com/2022/01/12/async-rust-in-practice-performance-pitfalls-profiling/">性能调优文章</a></p>
<p>为了降低系统调用的次数,我们需要使用一个写入缓冲区,当写入一个帧时,首先会写入该缓冲区,然后等缓冲区数据足够多时,再集中将其中的数据写入到 socket 中,这样就将多次系统调用优化减少到一次。</p>
<p>还有,缓冲区也不总是能提升性能。 例如,考虑一个 <code>bulk</code> 帧(多个帧放在一起组成一个 bulk通过批量发送提升效率),该帧的特点就是:由于由多个帧组合而成,因此帧体数据可能会很大。所以我们不能将其帧体数据写入到缓冲区中,因为数据较大时,先写入缓冲区再写入 socket 会有较大的性能开销(实际上缓冲区就是为了批量写入,既然 bulk 已经是批量了,因此不使用缓冲区也很正常)。</p>
<p>为了实现缓冲写,我们将使用 <a href="https://docs.rs/tokio/1/tokio/io/struct.BufWriter.html"><code>BufWriter</code></a> 结构体。该结构体实现了 <code>AsyncWrite</code> 特征,当 <code>write</code> 方法被调用时,不会直接写入到 socket 中,而是先写入到缓冲区中。当缓冲区被填满时,其中的内容会自动刷到(写入到)内部的 socket 中,然后再将缓冲区清空。当然,其中还存在某些优化,通过这些优化可以绕过缓冲区直接访问 socket。</p>
<p>由于篇幅有限,我们不会实现完整的 <code>write_frame</code> 函数,想要看完整代码可以访问<a href="https://github.com/tokio-rs/mini-redis/blob/tutorial/src/connection.rs#L159-L184">这里</a></p>
<p>首先,更新下 <code>Connection</code> 的结构体:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::io::BufWriter;
use tokio::net::TcpStream;
use bytes::BytesMut;
pub struct Connection {
stream: BufWriter&lt;TcpStream&gt;,
buffer: BytesMut,
}
impl Connection {
pub fn new(stream: TcpStream) -&gt; Connection {
Connection {
stream: BufWriter::new(stream),
buffer: BytesMut::with_capacity(4096),
}
}
}
<span class="boring">}</span></code></pre></pre>
<p>接着来实现 <code>write_frame</code> 函数:</p>
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use tokio::io::{self, AsyncWriteExt};
use mini_redis::Frame;
async fn write_frame(&amp;mut self, frame: &amp;Frame)
-&gt; io::Result&lt;()&gt;
{
match frame {
Frame::Simple(val) =&gt; {
self.stream.write_u8(b'+').await?;
self.stream.write_all(val.as_bytes()).await?;
self.stream.write_all(b&quot;\r\n&quot;).await?;
}
Frame::Error(val) =&gt; {
self.stream.write_u8(b'-').await?;
self.stream.write_all(val.as_bytes()).await?;
self.stream.write_all(b&quot;\r\n&quot;).await?;
}
Frame::Integer(val) =&gt; {
self.stream.write_u8(b':').await?;
self.write_decimal(*val).await?;
}
Frame::Null =&gt; {
self.stream.write_all(b&quot;$-1\r\n&quot;).await?;
}
Frame::Bulk(val) =&gt; {
let len = val.len();
self.stream.write_u8(b'$').await?;
self.write_decimal(len as u64).await?;
self.stream.write_all(val).await?;
self.stream.write_all(b&quot;\r\n&quot;).await?;
}
Frame::Array(_val) =&gt; unimplemented!(),
}
self.stream.flush().await;
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p>这里使用的方法由 <code>AsyncWriteExt</code> 提供,它们在 <code>TcpStream</code> 中也有对应的函数。但是在没有缓冲区的情况下最好避免使用这种逐字节的写入方式!不然,每写入几个字节就会触发一次系统调用,写完整个数据帧可能需要几十次系统调用,可以说是丧心病狂!</p>
<ul>
<li><code>write_u8</code> 写入一个字节</li>
<li><code>write_all</code> 写入所有数据</li>
<li><code>write_decimal</code>由 mini-redis 提供</li>
</ul>
<p>在函数结束前,我们还额外的调用了一次 <code>self.stream.flush().await</code>,原因是缓冲区可能还存在数据,因此需要手动刷一次数据:<code>flush</code> 的调用会将缓冲区中剩余的数据立刻写入到 socket 中。</p>
<p>当然,当帧比较小的时候,每写一次帧就 flush 一次的模式性能开销会比较大,此时我们可以选择在 <code>Connection</code> 中实现 <code>flush</code> 函数,然后将等帧积累多个后,再一次性在 <code>Connection</code> 中进行 flush。当然对于我们的例子来说简洁性是非常重要的因此选了将 <code>flush</code> 放入到 <code>write_frame</code> 中。</p>
<div id="giscus-container"></div>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../advance-practice/io.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../advance-practice/async.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../advance-practice/io.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../advance-practice/async.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="../ace.js"></script>
<script src="../editor.js"></script>
<script src="../mode-rust.js"></script>
<script src="../theme-dawn.js"></script>
<script src="../theme-tomorrow_night.js"></script>
<script src="../elasticlunr.min.js"></script>
<script src="../mark.min.js"></script>
<script src="../searcher.js"></script>
<script src="../clipboard.min.js"></script>
<script src="../highlight.js"></script>
<script src="../book.js"></script>
<script type="text/javascript" charset="utf-8">
var pagePath = "advance-practice/frame.md"
</script>
<!-- Custom JS scripts -->
<script src="../assets/custom.js"></script>
<script src="../assets/bigPicture.js"></script>
</div>
</body>
</html>