SQLAlchemy Tutorial 使用文档中文版

 python  SQLAlchemy Tutorial 使用文档中文版已关闭评论
1月 152018
 

原文链接:http://www.cnblogs.com/iwangzc/p/4112078.htmlsqlalchemy 官方文档:http://docs.sqlalchemy.org/en/latest/contents.html

1.版本检查

import sqlalchemy
sqlalchemy.__version__  

2.连接

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:',echo=True)

echo参数为True时,会显示每条执行的SQL语句,可以关闭。create_engine()返回一个Engine的实例,并且它表示通过数据库语法处理细节的核心接口,在这种情况下,数据库语法将会被解释称Python的类方法。

3.声明映像

当使用ORM1】时,构造进程首先描述数据库的表,然后定义我们用来映射那些表的类。在现版本的SQLAlchemy中,这两个任务通常一起执行,通过使用Declarative方法,我们可以创建一些包含描述要被映射的实际数据库表的准则的映射类。

使用Declarative方法定义的映射类依据一个基类,这个基类是维系类和数据表关系的目录——我们所说的Declarative base class。在一个普通的模块入口中,应用通常只需要有一个base的实例。我们通过declarative_base()功能创建一个基类:

from sqlalchemy.ext.declarativeimportdeclarative_base
Base = declarative_base()

有了这个base,我们可以依据这个base定义任意数量的映射类。一个简单的user例子:

from sqlalchemy import Column, Integer, String
class User(Base):
__tablename__= 'users'
id= Column(Integer, primary_key=True)
name = Column(String)

Declarative构造的一个类至少需要一个__tablename__属性,一个主键行。

4.构造模式(项目中没用到)

5.创建映射类的实例

ed_user = User(name='ed',fullname='Ed Jones', password='edspassword')

6.创建会话

现在我们已经准备毫和数据库开始会话了。ORM通过Session与数据库建立连接的。当应用第一次载入时,我们定义一个Session类(声明create_engine()的同时),这个Session类为新的Session对象提供工厂服务。

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)

这个定制的Session类会创建绑定到数据库的Session对象。如果需要和数据库建立连接,只需要实例化一个Session

session = Session()

虽然上面的Session已经和数据库引擎Engine关联,但是还没有打开任何连接。当它第一次被使用时,就会从Engine维护的一个连接池中检索是否存在连接,如果存在便会保持连接知道我们提交所有更改并且/或者关闭session对象。

7.添加新对象(简略)

ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
session.add(ed_user)

至此,我们可以认为,新添加的这个对象实例仍在等待中;ed_user对象现在并不代表数据库中的一行数据。直到使用flush进程,Session才会让SQL保持连接。如果查询这条数据的话,所有等待信息会被第一时间刷新,查询结果也会立即发行。

session.commit()

通过commit()可以提交所有剩余的更改到数据库。

8.回滚

session.rollback()

9.查询

通过Sessionquery()方法创建一个查询对象。这个函数的参数数量是可变的,参数可以是任何类或者是类的描述的集合。下面是一个迭代输出User类的例子:

for instance in session.query(User).order_by(User.id): 
print instance.name,instance.fullname

Query也支持ORM描述作为参数。任何时候,多个类的实体或者是基于列的实体表达都可以作为query()函数的参数,返回类型是元组:

for name, fullname in session.query(User.name,User.fullname): print name, fullname

Query返回的元组被命名为KeyedTuple类的实例元组。并且可以把它当成一个普通的Python数据类操作。元组的名字就相当于属性的属性名,类的类名一样。

 for row in session.query(User, User.name).all(): print row.User,row.name
<User(name='ed',fullname='Ed Jones', password='f8s7ccs')>ed

label()不知道怎么解释,看下例子就明白了。相当于row.name

for row in session.query(User.name.label('name_label')).all(): print(row.name_label) 

aliased()我的理解是类的别名,如果有多个实体都要查询一个类,可以用aliased()

from sqlalchemy.orm import aliased
user_alias = aliased(User, name='user_alias')
for row in session.query(user_alias,user_alias.name).all(): print row.user_alias

Query的 基本操作包括LIMITOFFSET,使用Python数组切片和ORDERBY结合可以让操作变得很方便。

for u in session.query(User).order_by(User.id)[1:3]: #只查询第二条和第三条数据 

9.1使用关键字变量过滤查询结果,filter 和 filter_by都适用。【2】使用很简单,下面列出几个常用的操作

query.filter(User.name == 'ed') #equals
query.filter(User.name != 'ed') #not equals
query.filter(User.name.like('%ed%')) #LIKE
uery.filter(User.name.in_(['ed','wendy', 'jack'])) #IN
query.filter(User.name.in_(session.query(User.name).filter(User.name.like('%ed%'))#IN
query.filter(~User.name.in_(['ed','wendy', 'jack']))#not IN
query.filter(User.name == None)#is None
query.filter(User.name != None)#not None
from sqlalchemy import and_
query.filter(and_(User.name =='ed',User.fullname =='Ed Jones')) # and
query.filter(User.name == 'ed',User.fullname =='Ed Jones') # and
query.filter(User.name == 'ed').filter(User.fullname == 'Ed Jones')# and
from sqlalchemy import or_
query.filter(or_(User.name =='ed', User.name =='wendy')) #or
query.filter(User.name.match('wendy')) #match

9.2.返回列表和数量(标量?)

all()返回一个列表:可以进行Python列表的操作。

query = session.query(User).filter(User.name.like('%ed')).order_by(User.id)
query.all()  
[<User(name='ed',fullname='EdJones', password='f8s7ccs')>,<User(name='fred',
fullname='FredFlinstone', password='blah')>]

first()适用于限制一个情况,返回查询到的第一个结果作为标量?:好像只能作为属性,类

query.first() <User(name='ed',fullname='Ed Jones', password='f8s7ccs')>

one()完全获取所有行,并且如果查询到的不只有一个对象或是有复合行,就会抛出异常。

from sqlalchemy.orm.exc import MultipleResultsFound
user = query.one()
try:  user = query.one()
except MultipleResultsFound, e:
 print e
Multiple rows were found for one()

如果一行也没有:

from sqlalchemy.orm.exc import NoResultFound
try:  user = query.filter(User.id == 99).one()
except NoResultFound, e:
 print e
No row was found for one()

one()方法对于想要解决“no items found”multiple items found”是不同的系统是极好的。(这句有语病啊)例如web服务返回,本来是在no results found情况下返回”404“的,结果在多个results found情况下也会跑出一个应用异常。

scalar()作为one()方法的依据,并且在one()成功基础上返回行的第一列。

query = session.query(User.id).filter(User.name == 'ed')
query.scalar() 7 

9.3.使用字符串SQL

字符串能使Query更加灵活,通过text()构造指定字符串的使用,这种方法可以用在很多方法中,像filter()order_by()

from sqlalchemy import text
for user in session.query(User).filter(text("id<224")).order_by(text("id")).all() 

绑定参数可以指定字符串,用params()方法指定数值。

session.query(User).filter(text("id<:value and name=:name")).\ params(value=224, name='fred').order_by(User.id).one()
 

如果要用一个完整的SQL语句,可以使用from_statement()

ession.query(User).from_statement(text("SELECT* FROM users where name=:name")).\
 params(name='ed').all()

也可以用from_statement()获取完整的”raw”,用字符名确定希望被查询的特定列:

session.query("id","name", "thenumber12").\ from_statement(text("SELECT id, name, 12 as ""thenumber12 FROM users where name=:name")).\

params(name=‘ed’).all()

[(1,u'ed', 12)]
感觉这个不太符合ORM的思想啊。。。

9.4 计数

count()用来统计查询结果的数量。

session.query(User).filter(User.name.like('%ed')).count()  

func.count()方法比count()更高级一点【3

from sqlalchemy import func
 session.query(func.count(User.name),User.name).group_by(User.name).all()  
[(1,u'ed'), (1,u'fred'), (1,u'mary'), (1,u'wendy')]

为了实现简单计数SELECT count(*) FROM table,可以这么写:

session.query(func.count('*')).select_from(User).scalar()  

如果我们明确表达计数是根据User表的主键的话,可以省略select_from(User):

session.query(func.count(User.id)).scalar()  

上面两行结果均为4

Go to (下)


10.建立联系(外键)

是时候考虑怎样映射和查询一个和Users表关联的第二张表了。假设我们系统的用户可以存储任意数量的email地址。我们需要定义一个新表AddressUser相关联。

from sqlalchemyimport ForeignKey from sqlalchemy.ormimport relationship, backref
class Address(Base):
__tablename__ = 'addresses'
id= Column(Integer, primary_key=True)
email_address = Column(String, nullable=False)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("User", backref=backref('addresses',order_by=id))
def__repr__(self):
 return"<Address(email_address='%s')>"%self.email_address

构造类和外键简单,就不过多赘述。主要说明以下relationship()函数:这个函数告诉ORMAddress类应该和User类连接起来,通过使用addresses.userrelationship()使用外键明确这两张表的关系。决定Adderess.user属性是多对一的。relationship()的子函数backref()提供表达反向关系的细节:relationship()对象的集合被User.address引用。多对一的反向关系总是一对多。更多的细节参考Basic RelRational Patterns

这两个互补关系:Address.userUser.addresses被称为双向关系。这是SQLAlchemy ORM的一个非常关键的功能。更多关系backref的细节参见Linking Relationships with Backref

假设声明的方法已经开始使用,relationship()中和其他类关联的参数可以通过strings指定。在上文的User类中,一旦所有映射成功,为了产生实际的参数,这些字符串会被当做Python的表达式。下面是一个在User类中创建双向联系的例子:

class User(Base):
addresses = relationship("Address", order_by="Address.id", backref="user")

一些知识:

在大多数的外键约束(尽管不是所有的)关系数据库只能链接到一个主键列,或具有唯一约束的列。

外键约束如果是指向多个列的主键,并且它本身也具有多列,这种被称为“复合外键”。

外键列可以自动更新自己来相应它所引用的行或者列。这被称为级联,是一种建立在关系数据库的功能

外键可以参考自己的表格。这种被称为“自引”外键。

我们需要在数据库中创建一个addresses表,所以我们会创建另一个元数据,这将会跳过已经创建的表。

11.操作主外键关联的对象

现在我们已经在User类中创建了一个空的addresser集合,可变集合类型,例如setdict,都可以用,但是默认的集合类型是list

jack = User(name='jack', fullname='Jack Bean', password='gjffdd')
jack.addresses
[]

现在可以直接在User对象中添加Address对象。只需要指定一个完整的列表:

jack.addresses = [Address(email_address='[email protected]'),Address(email_address='[email protected]')]
当使用双向关系时,元素在一个类中被添加后便会自动在另一个类中添加。这种行为发生在Python的更改事件属性中而不是用SQL语句:
>>> jack.addresses[1]
<Address(email_address='[email protected]')>
>>> jack.addresses[1].user
<User(name='jack', fullname='Jack Bean', password='gjffdd')>
jack提交到数据库中,再次查询Jack,(No SQL is yet issued for Jack’s addresses:)这句实在是翻译不了了,看看代码就明白是什么意思:
>>> jack = session.query(User).\ ...
filter_by(name='jack').one()  
>>> jack
<User(name='jack',fullname='Jack Bean', password='gjffdd')>

>>>jack.addresses  
[<Address(email_address='[email protected]')>, <Address(email_address='[email protected]')>]
当我们访问uaddresses集合时,SQL会被突然执行,这是一个延迟加载(lazy loading)关系的典型例子。现在addresses集合加载完成并且可以像对待普通列表一样对其进行操作。以后我们会优化这种加载方式。
12.使用JOINS查询
现在我们有了两张表,可以进行更多的查询操作,特别是怎样对两张表同时进行查询,Wikipediapage on SQL JOIN提供了很详细的说明,其中一些我们将在这里说明。之前用Query.filter()时,我们已经用过JOIN了,filter是一种简单的隐式join
>>>for u, a in session.query(User, Address).filter(User.id==Address.user_id).filter(Address.email_address=='[email protected]').all(): 
 print u
 print a
<User(name='jack',fullname='JackBean', password='gjffdd')>
<Address(email_address='[email protected]')>
Query.join()方法会更加简单:
>>>session.query(User).join(Address).\
... filter(Address.email_address=='[email protected]').\
... all()  
[<User(name='jack',fullname='JackBean', password='gjffdd')>]
之所以Query.join()知道怎么join两张表是因为它们之间只有一个外键。如果两张表中没有外键或者有一个以上的外键,当下列几种形式使用的时候,Query.join()可以表现的更好:
query.join(Address,User.id==Address.user_id)# 明确的条件
query.join(User.addresses)# 指定从左到右的关系
query.join(Address,User.addresses) #同样,有明确的目标
query.join('addresses') # 同样,使用字符串
 outerjoin()join()用法相同
query.outerjoin(User.addresses)# LEFT OUTER JOIN
12.1使用别名
当在多个表中查询时,如果同一张表需要被引用好几次,SQL通常要求对这个表起一个别名,因此,SQL可以区分对这个表进行的其他操作。Query也支持别名的操作。下面我们joinAddress实体两次,找到同时拥有两个不同email的用户:
>>>from sqlalchemy.ormimport aliased
>>>adalias1 = aliased(Address)
>>>adalias2 = aliased(Address)
>>>for username, email1, email2 in\
... session.query(User.name,adalias1.email_address,adalias2.email_address).\
... join(adalias1, User.addresses).\
... join(adalias2, User.addresses).\
... filter(adalias1.email_address=='[email protected]').\
... filter(adalias2.email_address=='[email protected]'):
... print username, email1,
email2  
jack
jack@google.com j25@yahoo.com
12.1使用子查询(暂时理解不了啊,多看代码研究吧:(
from sqlalchemy.sqlimport func
stmt = session.query(Address.user_id,func.count('*').\
...  label('address_count')).\
...  group_by(Address.user_id).subquery()
>>> for u, count in session.query(User,stmt.c.address_count).\
... outerjoin(stmt, User.id==stmt.c.user_id).order_by(User.id): 
 print u, count
<User(name='ed',fullname='EdJones', password='f8s7ccs')> None
<User(name='wendy',fullname='Wendy Williams', password='foobar')> None
<User(name='mary',fullname='Mary Contrary', password='xxg527')> None
<User(name='fred',fullname='Fred Flinstone', password='blah')> None
<User(name='jack',fullname='Jack Bean', password='gjffdd')> 2
12.2从子查询中选择实体?
上面的代码中我们只返回了包含子查询的一个列的结果。如果想要子查询映射到一个实体的话,使用aliased()设置一个要映射类的子查询别名:
>>> stmt = session.query(Address).\
... filter(Address.email_address!= '[email protected]').\
... subquery()
>>> adalias = aliased(Address, stmt) #?为什么有两个参数?
>>> for user, address in session.query(User, adalias).\
... join(adalias, User.addresses):  
... print user
... print address
<User(name='jack',fullname='Jack Bean', password='gjffdd')>
<Address(email_address='[email protected]')>

12.3使用EXISTS(存在?)

如果表达式返回任何行EXISTS为真,这是一个布尔值。它可以用在jions中,也可以用来定位在一个关系表中没有相应行的情况:

>>>from sqlalchemy.sqlimport exists
>>> stmt = exists().where(Address.user_id==User.id)
>>>for name, in session.query(User.name).filter(stmt): 
 print name
jack

等价于:

>>>for name, in session.query(User.name).\
... filter(User.addresses.any()):  
... print name
jack

any()限制行匹配:

>>>for name, in session.query(User.name).\
... filter(User.addresses.any(Address.email_address.like('%google%'))):  
... print name
jack

has()any()一样在应对多对一关系的情况下(注意“~“意味着”NOT”

>>> session.query(Address).\
... filter(~Address.user.has(User.name=='jack')).all()  
[]

12.4 常见的关系运算符

== = None 都是用在多对一中,而contains()用在一对多的集合中:

query.filter(Address.user == someuser)
query.filter(User.addresses.contains(someaddress))

Any()(用于集合中):

query.filter(User.addresses.any(Address.email_address == 'bar'))#also takes keyword arguments:
query.filter(User.addresses.any(email_address='bar'))

as()(用在标量?不在集合中):

query.filter(Address.user.has(name='ed'))

Query.with_parent()(所有关系都适用):

session.query(Address).with_parent(someuser,'addresses')

13 预先加载(跟性能有关)和lazy loading相对,建议直接查看文档吧

待补充。。。

Google Protocol Buffers 入门(protobuf tutorial译文)

 protobuf  Google Protocol Buffers 入门(protobuf tutorial译文)已关闭评论
6月 122016
 

分享好文, 转自:http://www.cnblogs.com/shitouer/archive/2013/04/10/google-protocol-buffers-tutorial.html , google-protocol-buffer-tutorial的中文翻译文章!


1. 前言

这篇入门教程是基于Java语言的,这篇文章我们将会:

  1. 创建一个.proto文件,在其内定义一些PB message
  2. 使用PB编译器
  3. 使用PB Java API 读写数据

这篇文章仅是入门手册,如果想深入学习及了解,可以参看: Protocol Buffer Language GuideJava API ReferenceJava Generated Code Guide, 以及Encoding Reference

2. 为什么使用Protocol Buffers

接下来用“通讯簿”这样一个非常简单的应用来举例。该应用能够写入并读取“联系人”信息,每个联系人由name,ID,email address以及contact photo number组成。这些信息的最终存储在文件中。

如何序列化并检索这样的结构化数据呢?有以下解决方案:

  1.  使用Java序列化(Java Serialization)。这是最直接的解决方式,因为该方式是内置于Java语言的,但是,这种方式有许多问题(Effective Java 对此有详细介绍),而且当有其他应用程序(比如C++ 程序及Python程序书写的应用)与之共享数据的时候,这种方式就不能工作了。
  2. 将数据项编码成一种特殊的字符串。例如将四个整数编码成“12:3:-23:67”。这种方法简单且灵活,但是却需要编写独立的,只需要用一次的编码和解码代码,并且解析过程需要一些运行成本。这种方式对于简单的数据结构非常有效。
  3. 将数据序列化为XML。这种方式非常诱人,因为易于阅读(某种程度上)并且有不同语言的多种解析库。在需要与其他应用或者项目共享数据的时候,这是一种非常有效的方式。但是,XML是出了名的耗空间,在编码解码上会有很大的性能损耗。而且呢,操作XML DOM数非常的复杂,远不如操作类中的字段简单。

Protocol Buffers可以灵活,高效且自动化的解决该问题,只需要:

  1. 创建一个.proto 文件,描述希望数据存储结构
  2. 使用PB compiler 创建一个类,该类可以高效的,以二进制方式自动编码和解析PB数据

该生成类提供组成PB数据字段的getter和setter方法,甚至考虑了如何高效的读写PB数据。更厉害的是,PB友好的支持字段拓展,拓展后的代码,依然能够正确的读取原来格式编码的数据。

3. 定义协议格式

首先需要创建一个.proto文件。非常简单,每一个需要序列化的数据结构,编码一个PB message,然后为message中的字段指明一个名字和类型即可。该“通讯簿”的.proto 文件addressbook.proto定义如下:

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
package tutorial;
 
option java_package = “com.example.tutorial”;
option java_outer_classname = “AddressBookProtos”;
 
message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;
 
  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }
 
  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }
 
  repeated PhoneNumber phone = 4;
}
message AddressBook {
  repeated Person person = 1;
}

可以看到,语法非常类似Java或者C++,接下来,我们一条一条来过一遍每句话的含义:

  • .proto文件以一个package声明开始。该声明有助于避免不同项目建设的命名冲突。Java版的PB,在没有指明java_package的情况下,生成的类默认的package即为此package。这里我们生命的java_package,所以最终生成的类会位于com.example.tutorial package下。这里需要强调一下,即使指明了java_package,我们建议依旧定义.proto文件的package。
  • 在package声明之后,紧接着是专门为java指定的两个选项:java_package 以及 java_outer_classname。java_package我们已经说过,不再赘述。java_outer_classname为生成类的名字,该类包含了所有在.proto中定义的类。如果该选项不显式指明的话,会按照驼峰规则,将.proto文件的名字作为该类名。例如“addressbook.proto”将会是“Addressbook”,“address_book.proto”即为“AddressBook”
  • java指定选项后边,即为message定义。每个message是一个包含了一系列指明了类型的字段的集合。这里的字段类型包含大多数的标准简单数据类型,包括bool,int32,float,double以及string。Message中也可以定义嵌套的message,例如“Person” message 包含“PhoneNumber” message。也可以将已定义的message作为新的数据类型,例如上例中,PhoneNumber类型在Person内部定义,但他是phone的type。在需要一个字段包含预先定义的一个列表的时候,也可以定义枚举类型,例如“PhoneType”。
  • 我们注意到, 每一个message中的字段,都有“=1”,“=2”这样的标记,这可不是初始化赋值,该值是message中,该字段的唯一标示符,在二进制编码时候会用到。数字1~15的表示需求少于一个字节,所以在编码的时候,有这样一个优化,你可以用1~15标记最常使用或者重复字段元素(repeated elements)。用16或者更大的数字来标记不太常用的可选元素。再重复字段中,每一个元素都需重复编码标签数字,所以,该优化对重复字段最佳(repeat fileds)。

message的没一个字段,都要用如下的三个修饰符(modifier)来声明:

  1. required:必须赋值,不能为空,否则该条message会被认为是“uninitialized”。build一个“uninitialized” message会抛出一个RuntimeException异常,解析一条“uninitialized” message会抛出一条IOException异常。除此之外,“required”字段跟“optional”字段并无差别。
  2. optional:字段可以赋值,也可以不赋值。假如没有赋值的话,会被赋上默认值。对于简单类型,默认值可以自己设定,例如上例的PhoneNumber中的PhoneType字段。如果没有自行设定,会被赋上一个系统默认值,数字类型会被赋为0,String类型会被赋为空字符串,bool类型会被赋为false。对于内置的message,默认值为该message的默认实例或者原型,即其内所有字段均为设置。当获取没有显式设置值的optional字段的值时,就会返回该字段的默认值。
  3. repeated:该字段可以重复任意次数,包括0次。重复数据的顺序将会保存在protocol buffer中,将这个字段想象成一个可以自动设置size的数组就可以了。

 Notice:应该格外小心定义Required字段。当因为某原因要把Required字段改为Optional字段是,会有问题,老版本读取器会认为消息中没有该字段不完整,可能会拒绝或者丢弃该字段(Google文档是这么说的,但是我试了一下,将required的改为optional的,再用原来required时候的解析代码去读,如果字段赋值的话,并不会出错,但是如果字段未赋值,会报这样错误:Exception in thread “main” com.google.protobuf.InvalidProtocolBufferException: Message missing required fields:fieldname)。在设计时,尽量将这种验证放在应用程序端的完成。Google的一些工程师对此也很困惑,他们觉得,required类型坏处大于好处,应该尽量仅适用optional或者repeated的。但也并不是所有的人都这么想。

如果想深入学习.proto文件书写,可以参考Protocol Buffer Language Guide。但是不要妄想会有类似于类继承这样的机制,Protocol Buffers不做这个…

4. 编译Protocol Buffers

定义好.proto文件后,接下来,就是使用该文件,运行PB的编译器protoc,编译.proto文件,生成相关类,可以使用这些类读写“通讯簿”没得message。接下来我们要做:

  1. 如果你还没有安装PB编译器,到这里现在安装:download the package
  2. 安装后,运行protoc,结束后会发现在项目com.example.tutorial package下,生成了AddressBookProtos.java文件:
1
2
3
protoc -I=$SRC_DIR –java_out=$DST_DIR $SRC_DIR/addressbook.proto
#for example
protoc -I=G:\workspace\protobuf\message –java_out=G:\workspace\protobuf\src\main\java G:\workspace\protobuf\messages\addressbook.proto

  • -I:指明应用程序的源码位置,假如不赋值,则有当前路径(说实话,该处我是直译了,并不明白是什么意思。我做了尝试,该值不能为空,如果为空,则提示赋了一个空文件夹,如果是当前路径,请用.代替,我用.代替,又提示不对。但是可以是任何一个路径,都运行正确,只要不为空);
  • –java_out:指明目的路径,即生成代码输出路径。因为我们这里是基于java来说的,所以这里是–java_out,相对其他语言,设置为相对语言即可
  • 最后一个参数即.proto文件

Notice:此处运行完毕后,查看生成的代码,很有可能会出现一些类没有定义等错误,例如:com.google cannot be resolved to a type等。这是因为项目中缺少protocol buffers的相应library。在Protocol Buffers的源码包里,你会发现java/src/main/java,将这下边的文件拷贝到你的项目,大概可以解决问题。我只能说大概,因为当时我在弄得时候,也是刚学,各种出错,比较恶心。有一个简单的方法,呵呵,对于懒汉来说。创建一个maven的java项目,在pom.xml中,添加Protocol Buffers的依赖即可解决所有问题~在pom.xml中添加如下依赖(注意版本):

1
2
3
4
5
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>2.5.0</version>
</dependency>

 5. Protocol Buffer Java API

5.1 产生的类及方法

接下来看一下PB编译器创建了那些类以及方法。首先会发现一个.java文件,其内部定义了一个AddressBookProtos类,即我们在addressbook.proto文件java_outer_classname 指定的。该类内部有一系列内部类,对应分别是我们在addressbook.proto中定义的message。每个类内部都有相应的Builder类,我们可以用它创建类的实例。生成的类及类内部的Builder类,均自动生成了获取message中字段的方法,不同的是,生成的类仅有getter方法,而生成类内部的Builder既有getter方法,又有setter方法。本例中Person类,其仅有getter方法,如图所示:

 但是Person.Builder类,既有getter方法,又有setter方法,如图:

person.builderperson.builder

从上边两张图可以看到:

  1. 每一个字段都有JavaBean风格的getter和setter
  2. 对于每一个简单类型变量,还对应都有一个has这样的一个方法,如果该字段被赋值了,则返回true,否则,返回false
  3. 对每一个变量,都有一个clear方法,用于置空字段

对于repeated字段:

repeated filedrepeated filed

从图上看:

  1. 从person.builder图上看出,对于repeated字段,还有一个特殊的getter,即getPhoneCount方法,及repeated字段还有一个特殊的count方法
  2. 其getter和setter方法根据index获取或设置一个数据项
  3. add()方法用于附加一个数据项
  4. addAll()方法来直接增加一个容器中的所有数据项

注意到一点:所有的这些方法均命名均符合驼峰规则,即使在.proto文件中是小写的。PB compiler生成的方法及字段等都是按照驼峰规则来产生,以符合基本的Java规范,当然,其他语言也尽量如此。所以,在proto文件中,命名最好使用用“_”来分割不同小写的单词。

 5.2 枚举及嵌套类

从代码中可以发现,还产生了一个枚举:PhoneType,该枚举位于Person类内部:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public enum PhoneType
        implements com.google.protobuf.ProtocolMessageEnum {
      /**
       * <code>MOBILE = 0;</code>
       */
      MOBILE(0,0),
      /**
       * <code>HOME = 1;</code>
       */
      HOME(1,1),
      /**
       * <code>WORK = 2;</code>
       */
      WORK(2,2),
      ;
      …
}

除此之外,如我们所预料,还有一个Person.PhoneNumber内部类,嵌套在Person类中,可以自行看一下生成代码,不再粘贴。

5.3 Builders vs. Messages

由PB compiler生成的消息类是不可变的。一旦一个消息对象构建出来,他就不再能够修改,就像java中的String一样。在构建一个message之前,首先要构建一个builder,然后使用builder的setter或者add()等方法为所需字段赋值,之后调用builder对象的build方法。

在使用中会发现,这些构造message对象的builder的方法,都又会返回一个新的builder,事实上,该builder跟调用这个方法的builder是同一方法。这样做的目的,仅是为了方便而已,我们可以把所有的setter写在一行内。

如下构造一个Person实例:

1
2
3
4
5
6
7
8
9
10
11
12
Person john = Person
        .newBuilder()
        .setId(1)
        .setName(“john”)
        .setEmail(“[email protected]”)
        .addPhone(
                PhoneNumber
                .newBuilder()
                .setNumber(“1861xxxxxxx”)
                .setType(PhoneType.WORK)
                .build()
        ).build();

5.4 标准消息方法

每一个消息类及Builder类,基本都包含一些公用方法,用来检查和维护这个message,包括:

  1.  isInitialized(): 检查是否所有的required字段是否被赋值
  2. toString(): 返回一个便于阅读的message表示(本来是二进制的,不可读),尤其在debug时候比较有用
  3. mergeFrom(Message other): 仅builder有此方法,将其message的内容与此message合并,覆盖简单及重复字段
  4. clear(): 仅builder有此方法,清空所有的字段

5.5 解析及序列化

对于每一个PB类,均提供了读写二进制数据的方法:

  1. byte[] toByteArray();: 序列化message并且返回一个原始字节类型的字节数组
  2. static Person parseFrom(byte[] data);: 将给定的字节数组解析为message
  3. void writeTo(OutputStream output);: 将序列化后的message写入到输出流
  4. static Person parseFrom(InputStream input);: 读入并且将输入流解析为一个message

这里仅列出了几个解析及序列化方法,完整列表,可以参见:Message API reference

6. 使用PB生成类写入

接下来使用这些生成的PB类,初始化一些联系人,并将其写入一个文件中。

下面的程序首先从一个文件中读取一个通讯簿(AddressBook),然后添加一个新的联系人,再将新的通讯簿写回到文件。

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.example.tutorial;
 
import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
 
class AddPerson {
    // This function fills in a Person message based on user input.
    static Person PromptForAddress(BufferedReader stdin, PrintStream stdout)
            throws IOException {
        Person.Builder person = Person.newBuilder();
 
        stdout.print(“Enter person ID: “);
        person.setId(Integer.valueOf(stdin.readLine()));
 
        stdout.print(“Enter name: “);
        person.setName(stdin.readLine());
 
        stdout.print(“Enter email address (blank for none): “);
        String email = stdin.readLine();
        if (email.length() >0) {
            person.setEmail(email);
        }
 
        while (true) {
            stdout.print(“Enter a phone number (or leave blank to finish): “);
            String number = stdin.readLine();
            if (number.length() ==0) {
                break;
            }
 
            Person.PhoneNumber.Builder phoneNumber = Person.PhoneNumber
                    .newBuilder().setNumber(number);
 
            stdout.print(“Is this a mobile, home, or work phone? “);
            String type = stdin.readLine();
            if (type.equals(“mobile”)) {
                phoneNumber.setType(Person.PhoneType.MOBILE);
            }else if (type.equals(“home”)) {
                phoneNumber.setType(Person.PhoneType.HOME);
            }else if (type.equals(“work”)) {
                phoneNumber.setType(Person.PhoneType.WORK);
            }else {
                stdout.println(“Unknown phone type.  Using default.”);
            }
 
            person.addPhone(phoneNumber);
        }
 
        return person.build();
    }
 
    // Main function: Reads the entire address book from a file,
    // adds one person based on user input, then writes it back out to the same
    // file.
    public static void main(String[] args)throws Exception {
        if (args.length !=1) {
            System.err.println(“Usage:  AddPerson ADDRESS_BOOK_FILE”);
            System.exit(-1);
        }
 
        AddressBook.Builder addressBook = AddressBook.newBuilder();
 
        // Read the existing address book.
        try {
            addressBook.mergeFrom(new FileInputStream(args[0]));
        }catch (FileNotFoundException e) {
            System.out.println(args[0]
                    +”: File not found.  Creating a new file.”);
        }
 
        // Add an address.
        addressBook.addPerson(PromptForAddress(new BufferedReader(
                new InputStreamReader(System.in)), System.out));
 
        // Write the new address book back to disk.
        FileOutputStream output =new FileOutputStream(args[0]);
        addressBook.build().writeTo(output);
        output.close();
    }
}

 7. 使用PB生成类读取

运行第六部分程序,写入几个联系人到文件中,接下来,我们就要读取联系人。程序入下:

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
40
41
42
43
44
45
46
47
48
package com.example.tutorial;
import java.io.FileInputStream;
 
import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
 
class ListPeople {
  // Iterates though all people in the AddressBook and prints info about them.
  static void Print(AddressBook addressBook) {
    for (Person person: addressBook.getPersonList()) {
      System.out.println(“Person ID: ” + person.getId());
      System.out.println(”  Name: ” + person.getName());
      if (person.hasEmail()) {
        System.out.println(”  E-mail address: ” + person.getEmail());
      }
 
      for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
        switch (phoneNumber.getType()) {
          case MOBILE:
            System.out.print(”  Mobile phone #: “);
            break;
          case HOME:
            System.out.print(”  Home phone #: “);
            break;
          case WORK:
            System.out.print(”  Work phone #: “);
            break;
        }
        System.out.println(phoneNumber.getNumber());
      }
    }
  }
 
  // Main function:  Reads the entire address book from a file and prints all
  //   the information inside.
  public static void main(String[] args)throws Exception {
    if (args.length !=1) {
      System.err.println(“Usage:  ListPeople ADDRESS_BOOK_FILE”);
      System.exit(-1);
    }
 
    // Read the existing address book.
    AddressBook addressBook =
      AddressBook.parseFrom(new FileInputStream(args[0]));
 
    Print(addressBook);
  }
}

至此我们已经可以使用生成类写入和读取PB message。

8. 拓展PB

当产品发布后,迟早有一天我们需要改善我们的PB定义。如果要做到新的PB能够向后兼容,同时老的PB又能够向前兼容,我们必须遵守如下规则:

  1. 千万不要修改现有字段后边的数值标签
  2. 千万不要增加或者删除required字段
  3. 可以删除optional或者repeated字段
  4. 可以添加新的optional或者repeated字段,但是必须使用新的数字标签(该数字标签必须从未在该PB中使用过,包括已经删除字段的数字标签)

如果违反了这些规则,会有一些相应的异常,可参见some exceptions,但是这些异常,很少很少会被用到。

遵守这些规则,老的代码可以正确的读取新的message,但是会忽略新的字段;对于删掉的optional的字段,老代码会使用他们的默认值;对于删除的repeated字段,则把他们置为空。

新的代码也将能够透明的读取老的messages。但是必须注意,新的optional字段在老的message中是不存在的,必须显式的使用has_方法来判断其是否设置了,或者在.proto 文件中以[default = value]形式提供默认值。如果没有指定默认值的话,会按照类型默认值赋值。对于string类型,默认值是空字符串。对于bool来说,默认值是false。对于数字类型,默认值是0。

9. 高级用法

Protocol Buffers的应用远远不止简单的存取以及序列化。如果想了解更多用法,可以去研究Java API reference

Protocol Message Class提供了一个重要特性:反射。不需要再写任何特殊的message类型就可以遍历一条message的所有字段以及操作字段的值。反射的一个非常重要的应用是可以将PBmessage与其他的编码语言进行转化,例如与XML或者JSON之间。

反射另外一个更加高级的应用应该是两个同一类型message的之间的不同,或者开发一种可以成为“Protocol Buffers 正则表达式”的应用,使用它,可以编写符合一定消息内容的表达式。

除此之外,开动脑筋,你会发现,Protocol Buffers能解决远远超过你刚开始对他的期待。

译自:https://developers.google.com/protocol-buffers/docs/javatutorial

protobuf 学习手册(tutorial)

 protobuf, 未分类  protobuf 学习手册(tutorial)已关闭评论
9月 162015
 

developers.google.com上的protobuf的学习教程(java版), 给不能翻墙的朋友

Protocol Buffer Basics: Java

This tutorial provides a basic Java programmer’s introduction to working with protocol buffers. By walking through creating a simple example application, it shows you how to

  • Define message formats in a .proto file.
  • Use the protocol buffer compiler.
  • Use the Java protocol buffer API to write and read messages.

This isn’t a comprehensive guide to using protocol buffers in Java. For more detailed reference information, see the Protocol Buffer Language Guide, the Java API Reference, the Java Generated Code Guide, and the Encoding Reference.

Why Use Protocol Buffers?

The example we’re going to use is a very simple “address book” application that can read and write people’s contact details to and from a file. Each person in the address book has a name, an ID, an email address, and a contact phone number.

How do you serialize and retrieve structured data like this? There are a few ways to solve this problem:

  • Use Java Serialization. This is the default approach since it’s built into the language, but it has a host of well-known problems (see Effective Java, by Josh Bloch pp. 213), and also doesn’t work very well if you need to share data with applications written in C++ or Python.
  • You can invent an ad-hoc way to encode the data items into a single string – such as encoding 4 ints as “12:3:-23:67”. This is a simple and flexible approach, although it does require writing one-off encoding and parsing code, and the parsing imposes a small run-time cost. This works best for encoding very simple data.
  • Serialize the data to XML. This approach can be very attractive since XML is (sort of) human readable and there are binding libraries for lots of languages. This can be a good choice if you want to share data with other applications/projects. However, XML is notoriously space intensive, and encoding/decoding it can impose a huge performance penalty on applications. Also, navigating an XML DOM tree is considerably more complicated than navigating simple fields in a class normally would be.

Protocol buffers are the flexible, efficient, automated solution to solve exactly this problem. With protocol buffers, you write a .proto description of the data structure you wish to store. From that, the protocol buffer compiler creates a class that implements automatic encoding and parsing of the protocol buffer data with an efficient binary format. The generated class provides getters and setters for the fields that make up a protocol buffer and takes care of the details of reading and writing the protocol buffer as a unit. Importantly, the protocol buffer format supports the idea of extending the format over time in such a way that the code can still read data encoded with the old format.

Where to Find the Example Code

The example code is included in the source code package, under the “examples” directory. Download it here.

Defining Your Protocol Format

To create your address book application, you’ll need to start with a .proto file. The definitions in a .proto file are simple: you add a message for each data structure you want to serialize, then specify a name and a type for each field in the message. Here is the .proto file that defines your messages, addressbook.proto.

package tutorial;

option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}

As you can see, the syntax is similar to C++ or Java. Let’s go through each part of the file and see what it does.

The .proto file starts with a package declaration, which helps to prevent naming conflicts between different projects. In Java, the package name is used as the Java package unless you have explicitly specified ajava_package, as we have here. Even if you do provide a java_package, you should still define a normalpackage as well to avoid name collisions in the Protocol Buffers name space as well as in non-Java languages.

After the package declaration, you can see two options that are Java-specific: java_package andjava_outer_classname. java_package specifies in what Java package name your generated classes should live. If you don’t specify this explicitly, it simply matches the package name given by the packagedeclaration, but these names usually aren’t appropriate Java package names (since they usually don’t start with a domain name). The java_outer_classname option defines the class name which should contain all of the classes in this file. If you don’t give a java_outer_classname explicitly, it will be generated by converting the file name to camel case. For example, “my_proto.proto” would, by default, use “MyProto” as the outer class name.

Next, you have your message definitions. A message is just an aggregate containing a set of typed fields. Many standard simple data types are available as field types, including bool, int32, float, double, andstring. You can also add further structure to your messages by using other message types as field types – in the above example the Person message contains PhoneNumber messages, while the AddressBookmessage contains Person messages. You can even define message types nested inside other messages – as you can see, the PhoneNumber type is defined inside Person. You can also define enum types if you want one of your fields to have one of a predefined list of values – here you want to specify that a phone number can be one of MOBILE, HOME, or WORK.

The ” = 1″, ” = 2″ markers on each element identify the unique “tag” that field uses in the binary encoding. Tag numbers 1-15 require one less byte to encode than higher numbers, so as an optimization you can decide to use those tags for the commonly used or repeated elements, leaving tags 16 and higher for less-commonly used optional elements. Each element in a repeated field requires re-encoding the tag number, so repeated fields are particularly good candidates for this optimization.

Each field must be annotated with one of the following modifiers:

  • required: a value for the field must be provided, otherwise the message will be considered “uninitialized”. Trying to build an uninitialized message will throw a RuntimeException. Parsing an uninitialized message will throw an IOException. Other than this, a required field behaves exactly like an optional field.
  • optional: the field may or may not be set. If an optional field value isn’t set, a default value is used. For simple types, you can specify your own default value, as we’ve done for the phone number type in the example. Otherwise, a system default is used: zero for numeric types, the empty string for strings, false for bools. For embedded messages, the default value is always the “default instance” or “prototype” of the message, which has none of its fields set. Calling the accessor to get the value of an optional (or required) field which has not been explicitly set always returns that field’s default value.
  • repeated: the field may be repeated any number of times (including zero). The order of the repeated values will be preserved in the protocol buffer. Think of repeated fields as dynamically sized arrays.

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use onlyoptional and repeated. However, this view is not universal.

You’ll find a complete guide to writing .proto files – including all the possible field types – in the Protocol Buffer Language Guide. Don’t go looking for facilities similar to class inheritance, though – protocol buffers don’t do that.

Compiling Your Protocol Buffers

Now that you have a .proto, the next thing you need to do is generate the classes you’ll need to read and writeAddressBook (and hence Person and PhoneNumber) messages. To do this, you need to run the protocol buffer compiler protoc on your .proto:

  1. If you haven’t installed the compiler, download the package and follow the instructions in the README.
  2. Now run the compiler, specifying the source directory (where your application’s source code lives – the current directory is used if you don’t provide a value), the destination directory (where you want the generated code to go; often the same as $SRC_DIR), and the path to your .proto. In this case, you…:

    protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto

    Because you want Java classes, you use the –java_out option – similar options are provided for other supported languages.

This generates com/example/tutorial/AddressBookProtos.java in your specified destination directory.

The Protocol Buffer API

Let’s look at some of the generated code and see what classes and methods the compiler has created for you. If you look in AddressBookProtos.java, you can see that it defines a class called AddressBookProtos, nested within which is a class for each message you specified in addressbook.proto. Each class has its ownBuilder class that you use to create instances of that class. You can find out more about builders in theBuilders vs. Messages section below.

Both messages and builders have auto-generated accessor methods for each field of the message; messages have only getters while builders have both getters and setters. Here are some of the accessors for the Personclass (implementations omitted for brevity):

	
// required string name = 1; public boolean hasName(); public String getName(); // required int32 id = 2; public boolean hasId(); public int getId(); // optional string email = 3; public boolean hasEmail(); public String getEmail(); // repeated .tutorial.Person.PhoneNumber phone = 4; public List<PhoneNumber> getPhoneList(); public int getPhoneCount(); public PhoneNumber getPhone(int index);

Meanwhile, Person.Builder has the same getters plus setters:

	
// required string name = 1; public boolean hasName(); public java.lang.String getName(); public Builder setName(String value); public Builder clearName(); // required int32 id = 2; public boolean hasId(); public int getId(); public Builder setId(int value); public Builder clearId(); // optional string email = 3; public boolean hasEmail(); public String getEmail(); public Builder setEmail(String value); public Builder clearEmail(); // repeated .tutorial.Person.PhoneNumber phone = 4; public List<PhoneNumber> getPhoneList(); public int getPhoneCount(); public PhoneNumber getPhone(int index); public Builder setPhone(int index, PhoneNumber value); public Builder addPhone(PhoneNumber value); public Builder addAllPhone(Iterable<PhoneNumber> value); public Builder clearPhone();

As you can see, there are simple JavaBeans-style getters and setters for each field. There are also has getters for each singular field which return true if that field has been set. Finally, each field has a clear method that un-sets the field back to its empty state.

Repeated fields have some extra methods – a Count method (which is just shorthand for the list’s size), getters and setters which get or set a specific element of the list by index, an add method which appends a new element to the list, and an addAll method which adds an entire container full of elements to the list.

Notice how these accessor methods use camel-case naming, even though the .proto file uses lowercase-with-underscores. This transformation is done automatically by the protocol buffer compiler so that the generated classes match standard Java style conventions. You should always use lowercase-with-underscores for field names in your .proto files; this ensures good naming practice in all the generated languages. See the style guide for more on good .proto style.

For more information on exactly what members the protocol compiler generates for any particular field definition, see the Java generated code reference.

Enums and Nested Classes

The generated code includes a PhoneType Java 5 enum, nested within Person:

	
public static enum PhoneType {   MOBILE(0, 0),   HOME(1, 1),   WORK(2, 2),   ;   ... }

The nested type Person.PhoneNumber is generated, as you’d expect, as a nested class within Person.

Builders vs. Messages

The message classes generated by the protocol buffer compiler are all immutable. Once a message object is constructed, it cannot be modified, just like a Java String. To construct a message, you must first construct a builder, set any fields you want to set to your chosen values, then call the builder’s build() method.

You may have noticed that each method of the builder which modifies the message returns another builder. The returned object is actually the same builder on which you called the method. It is returned for convenience so that you can string several setters together on a single line of code.

Here’s an example of how you would create an instance of Person:

	
Person john =   Person.newBuilder()     .setId(1234)     .setName("John Doe")     .setEmail("[email protected]")     .addPhone(       Person.PhoneNumber.newBuilder()         .setNumber("555-4321")         .setType(Person.PhoneType.HOME))     .build();

Standard Message Methods

Each message and builder class also contains a number of other methods that let you check or manipulate the entire message, including:

  • isInitialized(): checks if all the required fields have been set.
  • toString(): returns a human-readable representation of the message, particularly useful for debugging.
  • mergeFrom(Message other): (builder only) merges the contents of other into this message, overwriting singular fields and concatenating repeated ones.
  • clear(): (builder only) clears all the fields back to the empty state.

These methods implement the Message and Message.Builder interfaces shared by all Java messages and builders. For more information, see the complete API documentation for Message.

Parsing and Serialization

Finally, each protocol buffer class has methods for writing and reading messages of your chosen type using the protocol buffer binary format. These include:

  • byte[] toByteArray();: serializes the message and returns a byte array containing its raw bytes.
  • static Person parseFrom(byte[] data);: parses a message from the given byte array.
  • void writeTo(OutputStream output);: serializes the message and writes it to anOutputStream.
  • static Person parseFrom(InputStream input);: reads and parses a message from anInputStream.

These are just a couple of the options provided for parsing and serialization. Again, see the Message API reference for a complete list.

Protocol Buffers and O-O Design Protocol buffer classes are basically dumb data holders (like structs in C++); they don’t make good first class citizens in an object model. If you want to add richer behaviour to a generated class, the best way to do this is to wrap the generated protocol buffer class in an application-specific class. Wrapping protocol buffers is also a good idea if you don’t have control over the design of the .proto file (if, say, you’re reusing one from another project). In that case, you can use the wrapper class to craft an interface better suited to the unique environment of your application: hiding some data and methods, exposing convenience functions, etc. You should never add behaviour to the generated classes by inheriting from them. This will break internal mechanisms and is not good object-oriented practice anyway.

Writing A Message

Now let’s try using your protocol buffer classes. The first thing you want your address book application to be able to do is write personal details to your address book file. To do this, you need to create and populate instances of your protocol buffer classes and then write them to an output stream.

Here is a program which reads an AddressBook from a file, adds one new Person to it based on user input, and writes the new AddressBook back out to the file again. The parts which directly call or reference code generated by the protocol compiler are highlighted.

	
import com.example.tutorial.AddressBookProtos.AddressBook; import com.example.tutorial.AddressBookProtos.Person; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.PrintStream; class AddPerson {   // This function fills in a Person message based on user input.   static Person PromptForAddress(BufferedReader stdin,                                  PrintStream stdout) throws IOException {     Person.Builder person = Person.newBuilder();     stdout.print("Enter person ID: ");     person.setId(Integer.valueOf(stdin.readLine()));     stdout.print("Enter name: ");     person.setName(stdin.readLine());     stdout.print("Enter email address (blank for none): ");     String email = stdin.readLine();     if (email.length() > 0) {       person.setEmail(email);     }     while (true) {       stdout.print("Enter a phone number (or leave blank to finish): ");       String number = stdin.readLine();       if (number.length() == 0) {         break;       }       Person.PhoneNumber.Builder phoneNumber =         Person.PhoneNumber.newBuilder().setNumber(number);       stdout.print("Is this a mobile, home, or work phone? ");       String type = stdin.readLine();       if (type.equals("mobile")) {         phoneNumber.setType(Person.PhoneType.MOBILE);       } else if (type.equals("home")) {         phoneNumber.setType(Person.PhoneType.HOME);       } else if (type.equals("work")) {         phoneNumber.setType(Person.PhoneType.WORK);       } else {         stdout.println("Unknown phone type.  Using default.");       }       person.addPhone(phoneNumber);     }     return person.build();   }   // Main function:  Reads the entire address book from a file,   //   adds one person based on user input, then writes it back out to the same   //   file.   public static void main(String[] args) throws Exception {     if (args.length != 1) {       System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");       System.exit(-1);     ; }     AddressBook.Builder addressBook = AddressBook.newBuilder();     // Read the existing address book.     try {       addressBook.mergeFrom(new FileInputStream(args[0]));     } catch (FileNotFoundException e) {       System.out.println(args[0] + ": File not found.  Creating a new file.");     }     // Add an address.     addressBook.addPerson(       PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),                        System.out));     // Write the new address book back to disk.     FileOutputStream output = new FileOutputStream(args[0]);     addressBook.build().writeTo(output);     output.close();   } }

Reading A Message

Of course, an address book wouldn’t be much use if you couldn’t get any information out of it! This example reads the file created by the above example and prints all the information in it.

	
import com.example.tutorial.AddressBookProtos.AddressBook; import com.example.tutorial.AddressBookProtos.Person; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; class ListPeople {   // Iterates though all people in the AddressBook and prints info about them.   static void Print(AddressBook addressBook) {     for (Person person: addressBook.getPersonList()) {       System.out.println("Person ID: " + person.getId());       System.out.println("  Name: " + person.getName());       if (person.hasEmail()) {         System.out.println("  E-mail address: " + person.getEmail());       }       for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {         switch (phoneNumber.getType()) {           case MOBILE:             System.out.print("  Mobile phone #: ");             break;           case HOME:             System.out.print("  Home phone #: ");             break;           case WORK:             System.out.print("  Work phone #: ");             break;         }         System.out.println(phoneNumber.getNumber());       }     }   }   // Main function:  Reads the entire address book from a file and prints all   //   the information inside.   public static void main(String[] args) throws Exception {     if (args.length != 1) {       System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE");       System.exit(-1);     }     // Read the existing address book.     AddressBook addressBook =       AddressBook.parseFrom(new FileInputStream(args[0]));     Print(addressBook);   } }

Extending a Protocol Buffer

Sooner or later after you release the code that uses your protocol buffer, you will undoubtedly want to “improve” the protocol buffer’s definition. If you want your new buffers to be backwards-compatible, and your old buffers to be forward-compatible – and you almost certainly do want this – then there are some rules you need to follow. In the new version of the protocol buffer:

  • you must not change the tag numbers of any existing fields.
  • you must not add or delete any required fields.
  • you may delete optional or repeated fields.
  • you may add new optional or repeated fields but you must use fresh tag numbers (i.e. tag numbers that were never used in this protocol buffer, not even by deleted fields).

(There are some exceptions to these rules, but they are rarely used.)

If you follow these rules, old code will happily read new messages and simply ignore any new fields. To the old code, optional fields that were deleted will simply have their default value, and deleted repeated fields will be empty. New code will also transparently read old messages. However, keep in mind that new optional fields will not be present in old messages, so you will need to either check explicitly whether they’re set with has_, or provide a reasonable default value in your .proto file with [default = value] after the tag number. If the default value is not specified for an optional element, a type-specific default value is used instead: for strings, the default value is the empty string. For booleans, the default value is false. For numeric types, the default value is zero. Note also that if you added a new repeated field, your new code will not be able to tell whether it was left empty (by new code) or never set at all (by old code) since there is no has_ flag for it.

Advanced Usage

Protocol buffers have uses that go beyond simple accessors and serialization. Be sure to explore the Java API reference to see what else you can do with them.

One key feature provided by protocol message classes is reflection. You can iterate over the fields of a message and manipulate their values without writing your code against any specific message type. One very useful way to use reflection is for converting protocol messages to and from other encodings, such as XML or JSON. A more advanced use of reflection might be to find differences between two messages of the same type, or to develop a sort of “regular expressions for protocol messages” in which you can write expressions that match certain message contents. If you use your imagination, it’s possible to apply Protocol Buffers to a much wider range of problems than you might initially expect!

Reflection is provided as part of the Message and Message.Builder interfaces.

附源码:

==============addressbook.proto文件=======================

// See README.txt for information and build instructions.

package tutorial;

option java_package = “com.example.tutorial”;
option java_outer_classname = “AddressBookProtos”;

message Person {
  required string name = 1;
  required int32 id = 2;        // Unique ID number for this person.
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

// Our address book file is just one of these.
message AddressBook {
  repeated Person person = 1;
}

===========================================================

=======AddPerson.java==============================================

package com.example.tutorial;

// See README.txt for information and build instructions.

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;

class AddPerson {
  // This function fills in a Person message based on user input.
  static Person PromptForAddress(BufferedReader stdin,
                                 PrintStream stdout) throws IOException {
    Person.Builder person = Person.newBuilder();

    stdout.print(“Enter person ID: “);
    person.setId(Integer.valueOf(stdin.readLine()));

    stdout.print(“Enter name: “);
    person.setName(stdin.readLine());

    stdout.print(“Enter email address (blank for none): “);
    String email = stdin.readLine();
    if (email.length() > 0) {
      person.setEmail(email);
    }

    while (true) {
      stdout.print(“Enter a phone number (or leave blank to finish): “);
      String number = stdin.readLine();
      if (number.length() == 0) {
        break;
      }

      Person.PhoneNumber.Builder phoneNumber =
        Person.PhoneNumber.newBuilder().setNumber(number);

      stdout.print(“Is this a mobile, home, or work phone? “);
      String type = stdin.readLine();
      if (type.equals(“mobile”)) {
        phoneNumber.setType(Person.PhoneType.MOBILE);
      } else if (type.equals(“home”)) {
        phoneNumber.setType(Person.PhoneType.HOME);
      } else if (type.equals(“work”)) {
        phoneNumber.setType(Person.PhoneType.WORK);
      } else {
        stdout.println(“Unknown phone type.  Using default.”);
      }

      person.addPhone(phoneNumber);
    }

    return person.build();
  }

  // Main function:  Reads the entire address book from a file,
  //   adds one person based on user input, then writes it back out to the same
  //   file.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println(“Usage:  AddPerson ADDRESS_BOOK_FILE”);
      System.exit(-1);
    }

    AddressBook.Builder addressBook = AddressBook.newBuilder();

    // Read the existing address book.
    try {
      FileInputStream input = new FileInputStream(args[0]);
      try {
        addressBook.mergeFrom(input);
      } finally {
        try { input.close(); } catch (Throwable ignore) {}
      }
    } catch (FileNotFoundException e) {
      System.out.println(args[0] + “: File not found.  Creating a new file.”);
    }

    // Add an address.
    addressBook.addPerson(
      PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
                       System.out));

    // Write the new address book back to disk.
    FileOutputStream output = new FileOutputStream(args[0]);
    try {
      addressBook.build().writeTo(output);
    } finally {
      output.close();
    }
  }
}

======================================================

================ListPeople.java===============================

package com.example.tutorial;

// See README.txt for information and build instructions.

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;

class ListPeople {
  // Iterates though all people in the AddressBook and prints info about them.
  static void Print(AddressBook addressBook) {
    for (Person person: addressBook.getPersonList()) {
      System.out.println(“Person ID: ” + person.getId());
      System.out.println(”  Name: ” + person.getName());
      if (person.hasEmail()) {
        System.out.println(”  E-mail address: ” + person.getEmail());
      }

      for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
        switch (phoneNumber.getType()) {
          case MOBILE:
            System.out.print(”  Mobile phone #: “);
            break;
          case HOME:
            System.out.print(”  Home phone #: “);
            break;
          case WORK:
            System.out.print(”  Work phone #: “);
            break;
        }
        System.out.println(phoneNumber.getNumber());
      }
    }
  }

  // Main function:  Reads the entire address book from a file and prints all
  //   the information inside.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println(“Usage:  ListPeople ADDRESS_BOOK_FILE”);
      System.exit(-1);
    }

    // Read the existing address book.
    AddressBook addressBook =
      AddressBook.parseFrom(new FileInputStream(args[0]));

    Print(addressBook);
  }
}

问题:

1. 出现如下错误:“java.lang.UnsupportedOperationException: This is supposed to be overridden by subclasses.”

  • The .proto definition is converted to java using the 2.4.3 (or earlier) protoc.exe
  • You use the 2.5.0 protobuffers library

检查下使用使用了2.4.x版本的protoc,  我在使用ubuntu12.04时就碰到上面情况,以为安装了2.6,实际默认的protoc是2.4版本

2. 使用源码安装的protoc命令时,提示如下错误:error while loading shared libraries: libprotoc.so.9: cannot open shared object file: No such file or directory

    命令行界面输入:   

sudo ldconfig

DONE!!!