Swift Protobuf 初探 —— 继 XML 后,JSON 也要被淘汰了吗
Protocol Buffers 是什么?
Protocol buffers are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. —— Google Official Definition
简单地说,Protocol Buffers 就是一种轻量高效的结构化数据交换格式,语言无关、平台无关、可扩展。理解地直白粗暴一点就是“更厉害更面向未来的 JSON”,那么接下来我们就将通过 Swift 官方实现的 Protobuf 来一探究竟。
Swift Protobuf
从去掉软盘到干掉光驱,从摈弃 Flash 推广 HTML5 ,到现在干脆把标准音频接口抹去,苹果一向善于引领科技时尚,那么在面向未来的数据交换格式上自然不会落后,因此 Swift Protobuf 应运而生。
开始动手尝试吧
本来我想拿照官方示例来走一遍的,但这次正好有个绝佳的示例,既有客户端又有服务端,可以“做”享其成一次,其中还涉及到 Go 语言,趁此机会也可以把玩一番。
将 ProtoBufExample (https://github.com/KyoheiG3/ProtobufExample)克隆至本地,
➜ git clone https://github.com/KyoheiG3/ProtobufExample.git
➜ cd ProtobufExample
配置客户端
➜ cd ./ProtobufClient
➜ pod install
初始化服务端
➜ cd ./ProtobufServer
➜ swift build
// 创建工程文件,以便在 Xcode 下编辑
➜ swift package generate-xcodeproj
启动 API
➜ ./.build/debug/api
配置并启动服务 with Go
➜ go get github.com/golang/protobuf/protoc-gen-go
➜ go run server/api.go
-
有必要的话,先下载安装 Go 语言环境,并配置 $GOPATH
➜ mkdir ~/go
➜ export GOPATH=~/go
➜ export PATH=$PATH:$GOPATH/bin
体会 .proto
安装
protobuf
➜ brew install protobuf
用 Swift 编译
protobuf
➜ cd ./ProtobufServer
➜ swift build
➜ protoc --plugin=protoc-gen-swift=.build/debug/protoc-gen-swift --swift_out=../protos --proto_path=../protos ../protos/DataModel.proto
此时我们就能在 protos 这个输出目录下就可以看到刚刚生成的对应 .pb.swift 文件了。
/* * Generated by the protocol buffer compiler. * Source: DataModel.proto */ import Foundation import SwiftProtobuf public struct BookInfo: ProtobufGeneratedMessage { public var swiftClassName: String {return "BookInfo"} public var protoMessageName: String {return "BookInfo"} public var protoPackageName: String {return ""} public var jsonFieldNames: [String: Int] {return [ "id": 1, "title": 3, "author": 2, ]} public var protoFieldNames: [String: Int] {return [ "id": 1, "title": 3, "author": 2, ]} public var id: Int64 = 0 public var title: String = "" public var author: String = "" public init() {} ...... ...... ...... if !keys.isEmpty { try visitor.visitMapField(fieldType: ProtobufMap.self, value: keys, protoFieldNumber: 4, protoFieldName: "keys", jsonFieldName: "keys", swiftFieldName: "keys") } } public func _protoc_generated_isEqualTo(other: MyLibrary) -> Bool { if id != other.id {return false} if name != other.name {return false} if books != other.books {return false} if keys != other.keys {return false} return true } }
其中还包括了一些对 JSON 的友好兼容,感兴趣的朋友可以自己动手玩一下。
探索更多
Google Protocol Buffers
https://developers.google.com/protocol-buffers/
Swift Protobuf
https://github.com/apple/swift-protobuf
ProtobufExample – Github
https://github.com/KyoheiG3/ProtobufExample
深入理解 ProtoBuf
Google Protocol Buffer 的使用和原理 – IBM
https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/