1、这里主要是介绍Protobuf提供的序列化与反序列化的高效性。相对于传统的java提供的序列化来说,Protobuf的效率提高了很多倍。但是也有不足的地方,就是proto在对象序列化的时候抛弃了很多数据。比如:类的相关属性。只保留了数据部分。提高了传输的效率,减少带宽的占用。

  2、java的序列化和反序列化

  1)对象

import java.io.Serializable;

public class User implements Serializable{

    private String id;
private String name;
private String age; public User(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} @Override
public String toString() {
return "Usr{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}

  2)序列化和反序列化

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays; public class UserSerializable { public static void main(String[] args) {
try {
//序列化
User user = new User("1","user","25");
//序列化字节流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//对象读取
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(user);
//转换成字节
byte[] bytes = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(bytes));
//反序列化
//直接读取直接,用对象输入流直接读取出来
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
//读取后转成对应对象
User u = (User) objectInputStream.readObject();
System.out.println(u.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}

  3)效果(目的对比)

[-84, -19, 0, 5, 115, 114, 0, 30, 99, 111, 109, 46, 116, 114, 111, 121, 46, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 46, 106, 97, 118, 97, 46, 85, 115, 101, 114, 122, 36, 125, -10, 11, 54, -23, 51, 2, 0, 3, 76, 0, 3, 97, 103, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 76, 0, 2, 105, 100, 113, 0, 126, 0, 1, 76, 0, 4, 110, 97, 109, 101, 113, 0, 126, 0, 1, 120, 112, 116, 0, 2, 50, 53, 116, 0, 1, 49, 116, 0, 4, 117, 115, 101, 114]
Usr{id='1', name='user', age='25'}

  3、Protobuf的使用

  1)protoc.exe下载:https://pan.baidu.com/s/1gfaULwv 目的:这个主要是用来创建反序列化的Java文件

  2)proto文件

  编写一个.proto为后缀的文件,文件内容如下:

option java_package = "com.troy.application.proto";
option java_outer_classname = "UsrProto";
message Usr{
required string id = 1;
required string name = 2;
required string age = 3;
}

  说明:java_package class里面的package;java_outer_classname为输出类的名称;message可以当成class看;required要求必填;

  下面是具体java对应message的写法。

.proto类型

Java 类型

C++类型

备注

double

double

double

float

float

float

int32

int

int32

使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint32。

int64

long

int64

使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint64。

sint32

int

int32

使用可变长编码方式。有符号的整型值。编码时比通常的int32高效。

sint64

long

int64

使用可变长编码方式。有符号的整型值。编码时比通常的int64高效。

fixed32

int

uint32

总是4个字节。如果数值总是比总是比228大的话,这个类型会比uint32高效。

fixed64

long

uint64

总是8个字节。如果数值总是比总是比256大的话,这个类型会比uint64高效。

sfixed32

int

int32

总是4个字节。

fixed64

long

int64

总是8个字节。

bool

boolean

bool

string

String

string

一个字符串必须是UTF-8编码或者7-bit ASCII编码的文本。

bytes

ByteString

string

可能包含任意顺序的字节数据。

  3)生成Java序列化代码

  将.proto文件和protoc.exe 放在同一文件夹

  

  然后编写一个bat文件,或者用cmd命令执行

protoc ./user.proto --java_out=./

  最后会在当前目录生成一个文件

  将包里面的java文件拷到对应包下面就可以使用了

  4)proto的序列化和反序列化

  a、对象(为了检测序列化多少,采用同一个对象只是改了一下名称)

import java.io.Serializable;

public class Usr implements Serializable{

    private String id;
private String name;
private String age; public Usr(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} @Override
public String toString() {
return "Usr{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}

  b、proto序列化文件

public final class UsrProto {
private UsrProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface UsrOrBuilder extends
// @@protoc_insertion_point(interface_extends:Usr)
com.google.protobuf.MessageOrBuilder { /**
* <code>required string id = 1;</code>
*/
boolean hasId();
/**
* <code>required string id = 1;</code>
*/
String getId();
/**
* <code>required string id = 1;</code>
*/
com.google.protobuf.ByteString
getIdBytes(); /**
* <code>required string name = 2;</code>
*/
boolean hasName();
/**
* <code>required string name = 2;</code>
*/
String getName();
/**
* <code>required string name = 2;</code>
*/
com.google.protobuf.ByteString
getNameBytes(); /**
* <code>required string age = 3;</code>
*/
boolean hasAge();
/**
* <code>required string age = 3;</code>
*/
String getAge();
/**
* <code>required string age = 3;</code>
*/
com.google.protobuf.ByteString
getAgeBytes();
}
/**
* Protobuf type {@code Usr}
*/
public static final class Usr extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Usr)
UsrOrBuilder {
// Use Usr.newBuilder() to construct.
private Usr(com.google.protobuf.GeneratedMessage.Builder builder) {
super(builder);
}
private Usr() {
id_ = "";
name_ = "";
age_ = "";
} @Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Usr(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
id_ = bs;
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
name_ = bs;
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
age_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return UsrProto.internal_static_Usr_descriptor;
} protected FieldAccessorTable
internalGetFieldAccessorTable() {
return UsrProto.internal_static_Usr_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Usr.class, Builder.class);
} public static final com.google.protobuf.Parser<Usr> PARSER =
new com.google.protobuf.AbstractParser<Usr>() {
public Usr parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Usr(input, extensionRegistry);
}
}; @Override
public com.google.protobuf.Parser<Usr> getParserForType() {
return PARSER;
} private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private Object id_;
/**
* <code>required string id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string id = 1;</code>
*/
public String getId() {
Object ref = id_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
id_ = s;
}
return s;
}
}
/**
* <code>required string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} public static final int NAME_FIELD_NUMBER = 2;
private Object name_;
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public String getName() {
Object ref = name_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} public static final int AGE_FIELD_NUMBER = 3;
private Object age_;
/**
* <code>required string age = 3;</code>
*/
public boolean hasAge() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string age = 3;</code>
*/
public String getAge() {
Object ref = age_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
age_ = s;
}
return s;
}
}
/**
* <code>required string age = 3;</code>
*/
public com.google.protobuf.ByteString
getAgeBytes() {
Object ref = age_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
age_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false; if (!hasId()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasName()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasAge()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
} public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getIdBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getAgeBytes());
}
unknownFields.writeTo(output);
} private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size; size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getIdBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getAgeBytes());
}
size += unknownFields.getSerializedSize();
memoizedSerializedSize = size;
return size;
} private static final long serialVersionUID = 0L;
public static Usr parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Usr parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Usr parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Usr parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Usr parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Usr parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Usr parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Usr parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Usr parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Usr parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
} public static Builder newBuilder() { return new Builder(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Usr prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); } @Override
protected Builder newBuilderForType(
BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Usr}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Usr)
UsrOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return UsrProto.internal_static_Usr_descriptor;
} protected FieldAccessorTable
internalGetFieldAccessorTable() {
return UsrProto.internal_static_Usr_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Usr.class, Builder.class);
} // Construct using com.troy.application.proto.UsrProto.Usr.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
} private Builder(
BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
id_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
age_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
return this;
} public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return UsrProto.internal_static_Usr_descriptor;
} public Usr getDefaultInstanceForType() {
return Usr.getDefaultInstance();
} public Usr build() {
Usr result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
} public Usr buildPartial() {
Usr result = new Usr(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.id_ = id_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.name_ = name_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.age_ = age_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
} public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Usr) {
return mergeFrom((Usr)other);
} else {
super.mergeFrom(other);
return this;
}
} public Builder mergeFrom(Usr other) {
if (other == Usr.getDefaultInstance()) return this;
if (other.hasId()) {
bitField0_ |= 0x00000001;
id_ = other.id_;
onChanged();
}
if (other.hasName()) {
bitField0_ |= 0x00000002;
name_ = other.name_;
onChanged();
}
if (other.hasAge()) {
bitField0_ |= 0x00000004;
age_ = other.age_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
} public final boolean isInitialized() {
if (!hasId()) { return false;
}
if (!hasName()) { return false;
}
if (!hasAge()) { return false;
}
return true;
} public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Usr parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Usr) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_; private Object id_ = "";
/**
* <code>required string id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string id = 1;</code>
*/
public String getId() {
Object ref = id_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
id_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>required string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string id = 1;</code>
*/
public Builder setId(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
}
/**
* <code>required string id = 1;</code>
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000001);
id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>required string id = 1;</code>
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
} private Object name_ = "";
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public String getName() {
Object ref = name_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public Builder setName(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000002);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
} private Object age_ = "";
/**
* <code>required string age = 3;</code>
*/
public boolean hasAge() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string age = 3;</code>
*/
public String getAge() {
Object ref = age_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
age_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>required string age = 3;</code>
*/
public com.google.protobuf.ByteString
getAgeBytes() {
Object ref = age_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
age_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string age = 3;</code>
*/
public Builder setAge(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
age_ = value;
onChanged();
return this;
}
/**
* <code>required string age = 3;</code>
*/
public Builder clearAge() {
bitField0_ = (bitField0_ & ~0x00000004);
age_ = getDefaultInstance().getAge();
onChanged();
return this;
}
/**
* <code>required string age = 3;</code>
*/
public Builder setAgeBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
age_ = value;
onChanged();
return this;
} // @@protoc_insertion_point(builder_scope:Usr)
} // @@protoc_insertion_point(class_scope:Usr)
private static final Usr defaultInstance;static {
defaultInstance = new Usr();
} public static Usr getDefaultInstance() {
return defaultInstance;
} public Usr getDefaultInstanceForType() {
return defaultInstance;
} } private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Usr_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Usr_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
String[] descriptorData = {
"\n\nuser.proto\",\n\003Usr\022\n\n\002id\030\001 \002(\t\022\014\n\004name\030" +
"\002 \002(\t\022\013\n\003age\030\003 \002(\tB&\n\032com.troy.applicati" +
"on.protoB\010UsrProto"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_Usr_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Usr_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Usr_descriptor,
new String[] { "Id", "Name", "Age", });
} // @@protoc_insertion_point(outer_class_scope)
}

  c、proto的序列化与反序列化

import java.util.Arrays;

public class UsrSerializable {

    public static void main(String[] args) {
try {
//建立工具
UsrProto.Usr.Builder builder = UsrProto.Usr.newBuilder();
//设置参数
builder.setId("1").setName("user").setAge("25");
//建立对象
UsrProto.Usr usr = builder.build();
//序列化
byte[] bytes = usr.toByteArray();
System.out.println(Arrays.toString(bytes)); //反序列化
UsrProto.Usr u = UsrProto.Usr.parseFrom(bytes);
System.out.println(u);
} catch (Exception e) {
e.printStackTrace();
}
}
}

  4)结果对比:

[10, 1, 49, 18, 4, 117, 115, 101, 114, 26, 2, 50, 53]
id: "1"
name: "user"
age: "25"

  4、总结

  1)相对于java本身的序列化,proto的序列化精简了很多很多。

  2)从数据上面来看没有任何变化,但是proto抛弃了很多东西。

  3)这个在http的数据传输上面可以提高很多效率。

  4)相对来说,编写上面多做了很多事情,但是考虑数据传输等问题可以采用这种方式!

java之序列化与反序列化的更多相关文章

  1. java 对象序列化与反序列化

    Java序列化与反序列化是什么? 为什么需要序列化与反序列化? 如何实现Java序列化与反序列化? 本文围绕这些问题进行了探讨. 1.Java序列化与反序列化  Java序列化是指把Java对象转换为 ...

  2. Java对象序列化与反序列化一 JSON

    Java对象序列化与反序列化一 JSON 1. 依赖库 jackson-all-1.6.1.jar 2. 代码 public class Student {    private String nam ...

  3. Java对象序列化和反序列化的工具方法

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

  4. Java之序列化和反序列化

    序列化的对象: package test_demo.SerializableOper; import java.io.Serializable; /* * 序列化对象需要实现序列号接口 * */ pu ...

  5. Java基础—序列化与反序列化(转载)

    转载自: Java序列化与反序列化 1.Java序列化与反序列化 Java序列化是指把Java对象转换为字节序列的过程:而Java反序列化是指把字节序列恢复为Java对象的过程. 2.为什么需要序列化 ...

  6. Java 中序列化与反序列化

    一. 序列化和反序列化概念 Serialization(序列化)是一种将对象以一连串的字节描述的过程:反序列化deserialization是一种将这些字节重建成一个对象的过程.将程序中的对象,放入文 ...

  7. JAVA的序列化与反序列化

    一.为什么要进行序列化 再介绍之前,我们有必要先了解下对象的生命周期,我们知道Java对象的生命周期,也即Java中的远程方法调用RMI也会被用到,在网络中要传输对象的话,则必须要对对象进行序列化,关 ...

  8. 深入分析Java的序列化与反序列化

    序列化是一种对象持久化的手段.普遍应用在网络传输.RMI等场景中.本文通过分析ArrayList的序列化来介绍Java序列化的相关内容.主要涉及到以下几个问题: 怎么实现Java的序列化 为什么实现了 ...

  9. Java 对象序列化和反序列化

         之前的文章中我们介绍过有关字节流字符流的使用,当时我们对于将一个对象输出到流中的操作,使用DataOutputStream流将该对象中的每个属性值逐个输出到流中,读出时相反.在我们看来这种行 ...

随机推荐

  1. IIS 7.5 配置 php 5.4.22 链接 sql 2008(用PDO链接数据库)

    最近在接触PHP这块,关于在wndows系统下的php配置,虽然网上已经很多文章,但有时候有些配置找起也麻烦,所以分享给大家. 一.php 5.4.22 下载地址 http://windows.php ...

  2. css3 抖动

    1. html <div id="wrapper"> <section> <p class="shake freez shake-hard& ...

  3. sed:轻量级流编辑器

    一. sed命令 sed是一种几乎包括在所有UNIX平台(包括Linux)的轻量级流编辑器.sed主要是用来将数据进行选取.替换.删除.新增的命令 注意:vi命令只能修改文件,但不能修改命令的结果,如 ...

  4. UVA-1660 Cable TV Network (最小割)

    题目大意:给一张n个点.m条边的无向图,求最小点割集的基数. 题目分析:求无向图最小点割集的基数可以变成求最小割.考虑单源s单汇t的无向图,如果要求一个最小点集,使得去掉这个点集后图不再连通(连通分量 ...

  5. UVA-307 Sticks (DFS+剪枝)

    题目大意:用n根长度未必相等的木棒匹配出最多数量的等长木棒. 题目分析:枚举所有可能的等长木棒的长度,通过DFS的方式逐根匹配,在此过程中要剪枝.先将木棒长度按从大到小排序,也就是说匹配每一根等长木棒 ...

  6. APP推广运营经验总结

    这片文章来自于我在公司的分享会,主题是关于APP在渠道方面的推广,主要包括3个方面,下载量,留存率,日活跃用户. 首先,在应用市场中,一个APP有四个方面,简介,截图,下载量,评论.用户看这四个方面, ...

  7. Granting and Managing Item Level Permission using SharePoint2013 Designer Workflow

    https://gnanasivamgunasekaran.wordpress.com/2015/12/29/granting-and-managing-item-level-permission-u ...

  8. RGB2YCbCr RGB2Gray

    Y = 0.2990R+0.5870G+0.1140B;                        Cb=-0.1687R-0.3313G+0.5000B+128;                 ...

  9. Web开发框架之权限管理系统

    Web开发框架之权限管理系统 记得我在很早之前,开始介绍我的Winform开发框架和我的WCF开发框架之初,我曾经给出下面的视图,介绍我整理的一个框架体系,其中包含有WInform开发框架以及我的We ...

  10. Python 编程核心知识体系-基础|数据类型|控制流(一)

    Python知识体系思维导图: 基础知识 数据类型 1.序列 2.字符串 3.列表和元组 4.字典和集合 循环 & 判断