强曰为道

与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

MessagePack 序列化完全指南

MessagePack 序列化完全指南 / The Complete Guide to MessagePack Serialization

一套由浅入深的 MessagePack 二进制序列化协议完整教程。 A comprehensive MessagePack binary serialization protocol tutorial, from shallow to deep.


目录 / Table of Contents

#章节 / Chapter关键词 / Keywords
1MessagePack 概述 / IntroductionWhat, Why, JSON, Protobuf, Avro
2格式规范 / Format SpecificationTypes, Binary, Extension, Fixnum
3Python 实践 / Python Implementationmsgpack-python, Custom, Streaming
4JavaScript 实践 / JavaScript Implementation@msgpack/msgpack, Browser, Node.js
5Go 实践 / Go Implementationvmihailenco/msgpack, Struct Tag
6Java 实践 / Java Implementationmsgpack-core, Annotation, Template
7Rust 实践 / Rust Implementationrmp-serde, Zero-copy, Performance
8流式处理 / StreamingUnbounded, Multi-message, RPC
9Docker 中的使用 / Docker UsageMicroservices, Network, Cache
10最佳实践 / Best PracticesSelection, Compat, Security, Debug

什么是 MessagePack? / What is MessagePack?

MessagePack(简称 msgpack)是一种高效的二进制序列化格式(Binary Serialization Format),能够在保持跨语言、跨平台互操作性的同时,比 JSON 更小、更快。

MessagePack (abbreviated as msgpack) is an efficient binary serialization format that is smaller and faster than JSON while maintaining cross-language, cross-platform interoperability.

核心特性 / Core Features:

特性 / Feature说明 / Description
紧凑 / Compact比 JSON 小 30%–50% / 30%–50% smaller than JSON
快速 / Fast序列化/反序列化速度接近 Protocol Buffers / Speed comparable to Protocol Buffers
跨语言 / Cross-language支持 50+ 编程语言 / Supported in 50+ languages
Schema-free无需预定义 Schema,类似 JSON / No predefined schema needed, like JSON
类型丰富 / Rich Types支持整数、浮点、字符串、二进制、数组、映射、扩展类型 / Supports int, float, string, binary, array, map, extension

适用场景 / When to Use

场景 / Scenario推荐度 / Recommendation说明 / Notes
高频 RPC 调用⭐⭐⭐⭐⭐体积小、解析快,降低网络开销
实时消息推送⭐⭐⭐⭐⭐WebSocket / MQTT 场景下优势明显
缓存序列化⭐⭐⭐⭐替代 JSON 作为 Redis/内存缓存格式
日志收集⭐⭐⭐⭐结构化日志压缩传输
配置文件⭐⭐可读性差,不如 YAML/TOML
前后端 API⭐⭐⭐需要浏览器端额外库,JSON 更通用

与其他格式对比 / Comparison with Other Formats

维度 / DimensionJSONMessagePackProtobufAvro
可读性 / Readability✅ 文本❌ 二进制❌ 二进制❌ 二进制
Schema 要求不需要不需要必须 .proto必须 .avsc
体积 / Size基准-30%~-50%-50%~-70%-50%~-70%
速度 / Speed基准2x~5x5x~10x5x~8x
跨语言 / Languages全部50+12+10+
动态类型 / Dynamic部分
学习曲线极低中高

阅读建议 / How to Read

  • 初学者 / Beginners: 从第 1 章开始,按顺序阅读 / Start from Chapter 1, read in order.
  • 有经验者 / Experienced: 直接跳到你使用的语言章节 / Jump to your language chapter.
  • 架构师 / Architects: 重点阅读第 1、2、8、10 章 / Focus on Chapters 1, 2, 8, 10.

每章结构 / Chapter Structure:

  • 📖 概念 — 核心知识点 / Concepts — core knowledge
  • 💻 代码 — 多语言示例 / Code — multi-language examples
  • ⚠️ 注意事项 — 常见陷阱 / Pitfalls — common traps
  • 🔗 扩展阅读 — 深入资料 / Further reading — deep dive

快速开始 / Quick Start

如果你已经了解 MessagePack,选择你的语言直接开始:

If you already know MessagePack, pick your language and get started:

语言 / Language库 / Library安装 / Install
Pythonmsgpackpip install msgpack
JavaScript@msgpack/msgpacknpm i @msgpack/msgpack
Gogithub.com/vmihailenco/msgpack/v5go get
Javamsgpack-coreMaven/Gradle 依赖
Rustrmp-serdecargo add rmp-serde
# Python Quick Start
import msgpack

data = {"name": "Alice", "scores": [95, 87, 92]}
packed = msgpack.packb(data)        # 序列化 / Serialize
unpacked = msgpack.unpackb(packed)   # 反序列化 / Deserialize
print(unpacked)  # {'name': b'Alice', 'scores': [95, 87, 92]}
// JavaScript Quick Start
import { encode, decode } from "@msgpack/msgpack";

const data = { name: "Alice", scores: [95, 87, 92] };
const encoded = encode(data);   // 序列化 / Serialize
const decoded = decode(encoded); // 反序列化 / Deserialize
console.log(decoded); // { name: "Alice", scores: [95, 87, 92] }

📝 版本说明 / Version Note: 本教程基于 MessagePack 规范版本 5(Revision 5),各语言库的 API 以 2025 年最新稳定版为准。

This tutorial is based on MessagePack Specification Revision 5. Language library APIs reflect the latest stable versions as of 2025.