protobuf-java中的一些小技巧

来源:互联网 发布:mac卸载 landesk 编辑:程序博客网 时间:2024/06/06 06:59

1、json字符串和pb对象之间的转换:

1)pom.xml

<dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>2.5.0</version></dependency><dependency>  <groupId>com.googlecode.protobuf-java-format</groupId>  <artifactId>protobuf-java-format</artifactId>  <version>1.2</version>  </dependency>
2)pb消息定义:

option java_package = "com.abc.proto";option java_outer_classname="HelloWordPB";message HelloWord {    optional int64 id = 1;    optional string name = 2;    repeated string recId = 3;}

3)java代码:

public class PBTest {public static void main(String[] args) {JSONObject jo = new JSONObject();JSONArray ja = new JSONArray();ja.add("1");ja.add("2");jo.put("id", 123456);//这里不能是字符串类型,否则pb会报错jo.put("name", "test");jo.put("recId", ja);String jsonStr = jo.toJSONString();System.out.println(jsonStr);//json > pbBuilder newBuilder = HelloWordPB.HelloWord.newBuilder();try {JsonFormat.merge(jsonStr, newBuilder);System.out.println(newBuilder.build().toString());} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}//pb > jsonString printToString = JsonFormat.printToString(newBuilder.build());System.out.println(printToString);}}
输出:

{"name":"test","id":123456,"recId":["1","2"]}id: 123456name: "test"recId: "1"recId: "2"{"id": 123456,"name": "test","recId": ["1","2"]}

2、pb在构造Builder的时候可以传入一个pb对象:

1)假设我们从redis中读取了一个pb二进制数据,然后反序列化成pb对象:

com.abc.proto.UserRecHistoryPB.UserRecHistory userRecHistory = null;String KEY = MessageFormat.format(CacheConstants.CACHE_KEY_USER_HISTORY_PERF, deviceId);byte[] bs = couchbaseHistoryDao.get(KEY);if (bs != null) {userRecHistory = UserRecHistoryPB.UserRecHistory.parseFrom(bs);}
2)接下来对userRecHistory进行修改,修改完毕后需要再保存到redis中:

Builder recHistoryBuilder = UserRecHistoryPB.UserRecHistory.newBuilder(userRecHistory);//修改UserRecHistory build = recHistoryBuilder.build();String KEY = MessageFormat.format(CacheConstants.CACHE_KEY_USER_HISTORY_PERF, deviceId);int ttl = (int)(System.currentTimeMillis()/1000)+CacheConstants.CACHE_TIME_QUARTER;couchbaseHistoryDao.set(KEY, ttl, build.toByteArray());




原创粉丝点击