protobufæ¯è°·æå®ä¹çä¸ç§è¯è¨æ å ³ãå¹³å°æ å ³çæ°æ®äº¤æ¢æ ¼å¼ï¼å¯ä»¥å°å¯¹è±¡åºåå为åèæ°ç»ãå°åèæ°ç»ååºåå为对象ã protobufæ¯æå¤ç§ç¼ç¨è¯è¨ï¼è¿é使ç¨çæ¯javaçprotobuf2.5.0çæ¬ PS:ç°å¨å¨protobufçgithubéï¼æèççæ¬æ¯2.7ï¼ä½æ¯å 为平æ¶å·¥ä½çå·¥ç¨éç¨ç2.5çæ¬ï¼çµèéçç¯å¢ä¹æ¯2.5çï¼ä½çæ¬protobufå¯ä»¥ç¾åº¦æå°èµæº ç¼è¯å¾å°protocå·¥å ·ï¼ä¸è½½protobufç æºç ï¼è¿å ¥æºç ç®å½å ./configure --prefix=/usr/local/protobuf2.5 è¦å®è£ å°çç®å½ make install # PSï¼ä¹åè¿ç¨è¿2.3çæ¬protobufï¼makeæ¶ä¼æ¥éï¼è§£å³æ¹æ³ï¼ # å¨src/google/protobuf/message.ccä¸ï¼æ·»å `#include<istream>`
å®è£ å®æåä¼å¨/usr/local/protobuf2.5ä¸çæbinãincludeãlibä¸ä¸ªæ件夹ï¼æ们è¦ç¨çæ¯binä¸çprotocå·¥å ·:
/usr/local/protobuf2.5/bin/protoc --proto_path=. --java_out=/Users/laifuzhi/IdeaProjects/template/src/main/java/ MyProto.proto
该å½ä»¤ä¼å°å½åæ件夹ä¸çMyProto.protoæ件转æ¢ä¸ºä¸ä¸ªjavaæºæ件ï¼æ¾å°/Users/laifuzhi/IdeaProjects/template/src/main/java/ç®å½ä¸å·¥ç¨ä¸å¼å ¥protobufçjarå ï¼åprotocççæ¬ä¿æä¸è´ï¼å¯ä»¥éè¿protocç--versionåæ°æ¥çprotocççæ¬ <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>2.5.0</version> </dependency>
ç¼è¾protobufæä»¶ï¼ option java_package = "com.lfz.proto"; //转æ¢åçjavaæºæ件å å option java_outer_classname = "FirstModule"; //转æ¢åçjavaæºæ件æ件åãç±»å //demo message CommonBean { required int32 id [default = 0] = 1; //ç¼å· required string name = 2; //å§å optional string address = 3; //å°å repeated string messages = 4; //æ¶æ¯çlist
使ç¨ä¹ æ¯ï¼å°ä¸ä¸ªæ¨¡åä¸éè¦ä½¿ç¨çbeanå®ä¹å°ä¸ä¸ªprotoæ件ä¸ç»ä¸ç®¡ç
ç®åç¨æ³ï¼requiredä¸ºå¿ å¡«é¡¹ï¼åºååååºååå¿ é¡»æå¼ï¼optional为å¯é项ï¼repeated为listéåï¼æ¯ä¸ªå±æ§å¿ é¡»æä¸ä¸ªkeyï¼ä¸è¬æ¯ä»1ä¸ç´éå¢ï¼å¯ä»¥ç»å±æ§è®¾ç½®é»è®¤å¼ãprotobufçæ´å¤æ ¼å¼å¯ä»¥çè¿é代ç ä¸çåºæ¬ä½¿ç¨ FirstModule.CommonBean.Builder builder = FirstModule.CommonBean.newBuilder(); builder.setId(1).setName("lfz"); //idånameæ¯requiredçï¼æä»¥å¿ å¡« FirstModule.CommonBean bean1 = builder.build(); byte[] bytes = bean1.toByteArray(); //åºåå FirstModule.CommonBean bean2 = FirstModule.CommonBean.parseFrom(bytes); //ååºåå
ä¹åå·¥ä½ä¸éè¦å°protobuf对象转æ¢ä¸ºjsonï¼ä½¿ç¨jacksonçå·¥å ·ä¸è½ç´æ¥è½¬æ¢ï¼éè¦ä½¿ç¨ç¬¬ä¸æ¹å·¥å ·:
<dependency> <groupId>com.googlecode.protobuf-java-format</groupId> <artifactId>protobuf-java-format</artifactId> <version>1.2</version> </dependency>
ç°å¨æé«1.4çæ¬ï¼å1.2çæ¬ç¨èµ·æ¥ä¸ä¸æ ·
å°ä¸é¢çprotobuf转为json并æå°ï¼
FirstModule.CommonBean.Builder builder = FirstModule.CommonBean.newBuilder(); builder.setId(1).setName("lfz"); FirstModule.CommonBean bean1 = builder.build(); System.out.println(JsonFormat.printToString(bean1)); byte[] bytes = bean1.toByteArray(); //æ¯javaçåºååçäºå¾å¤ FirstModule.CommonBean bean2 = FirstModule.CommonBean.parseFrom(bytes); System.out.println(JsonFormat.printToString(bean2));
1.4çæ¬çJsonFormat没æéæå·¥å ·æ¹æ³äºï¼éè¦å newåºæ¥JsonFormatå使ç¨ï¼æè§ä¸æ¹ä¾¿
protobuf-javaç使ç¨
åæ° 520
é
读 5760