Swift Protobuf 初探 —— 继 XML 后,JSON 也要被淘汰了吗

来源:互联网 发布:韩国bj 知乎 编辑:程序博客网 时间:2024/05/29 15:55

250f7ef7723ddc0cb3fe.jpg

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 克隆至本地

1
2
? git clone https://github.com/KyoheiG3/ProtobufExample.git
? cd ProtobufExample

配置客户端

1
2
? cd ./ProtobufClient
? pod install

初始化服务端

1
2
3
4
? cd ./ProtobufServer
? swift build
// 创建工程文件,以便在 Xcode 下编辑
? swift package generate-xcodeproj

启动 API

1
? ./.build/debug/api

配置并启动服务 with Go

1
2
? go get github.com/golang/protobuf/protoc-gen-go
? go run server/api.go

有必要的话,先下载安装 Go 语言环境,并配置 $GOPATH

1
2
3
? mkdir ~/go
? export GOPATH=~/go
? export PATH=$PATH:$GOPATH/bin

体会 .proto

安装 protobuf

1
? brew install protobuf

用 Swift 编译 protobuf

1
2
3
? 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 文件了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * 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<protobufstring,protobufstring>.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
  }
}</protobufstring,protobufstring>

其中还包括了一些对 JSON 的友好兼容,感兴趣的朋友可以自己动手玩一下。

探索更多

  • Google Protocol Buffers

  • Swift Protobuf

  • ProtobufExample - Github

深入理解 ProtoBuf

Google Protocol Buffer 的使用和原理 - IBM

0 0
原创粉丝点击