Protocol Buffers—-java

Protocol Buffers—-java

Protocol Buffers使用小示例

官方文档

1.添加maven依赖

<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.7.1</version>
</dependency>

2.下载系统对应的protoc

https://github.com/protocolbuffers/protobuf/releases

如windows使用:

3.解压并配置环境变量

解压并将protoc-3.7.0-rc-2-win64\bin加入环境变量

再cmd下执行

protoc --version

输出版本号则代表配置成功

libprotoc 3.7.0

4.编写 .proto文件

我在我的maven工程下的java同级目录下建了这个文件,文件和

addressbook.proto

syntax = "proto2";

package tutorial;

//生产的java文件所在包名
option java_package = "com.example.tutorial";
//生成的java文件类名,不指定则用.proto文件名驼峰后的名字
option java_outer_classname = "AddressBookProtos";

//联系人结构
message Person {
//后面的数字是tag,唯一性,建议使用1-15(性能最佳)
  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;
    //可指定默认值,不指定就使用Proto的系统默认值,具体值可看官方文档
    optional PhoneType type = 2 [default = HOME]; 
  }

  repeated PhoneNumber phones = 4;
}

//电话本结构
message AddressBook {
  repeated Person people = 1;
}
  • required 必须
  • optional 可有可无
  • repeated 可重复(相当于动态数组)

5.编译.proto文件生成java文件

执行:

protoc --java_out=[目标文件夹地址] [*.proto]

如我已进入.proto文件所在目录:

C:\MyWork\ideaWork\schoolmate\src\main\proto>protoc --java_out=../java addressbook.proto

红色的为生成的文件:

6.使用

官方案例:做一个通讯录的功能,可以从文件中添加联系人信息,并读取出来

具体可看:https://developers.google.com/protocol-buffers/docs/javatutorial#the-protocol-buffer-api

AddPerson.java

package com.example.tutorial;

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;

import java.io.*;
/**
 * @program: schoolmate
 * @description: 添加联系人
 * @author: page_yang
 * @create: 2019-04-24 15:16
 **/
public 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.addPhones(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.addPeople(
                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();
    }
}

ListPeople.java

package com.example.tutorial;

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;

import java.io.FileInputStream;
/**
 * @program: schoolmate
 * @description: 显示列表
 * @author: page_yang
 * @create: 2019-04-24 15:19
 **/
public class ListPeople {
    // Iterates though all people in the AddressBook and prints info about them.
    static void Print(AddressBook addressBook) {
        for (Person person: addressBook.getPeopleList()) {
            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.getPhonesList()) {
                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);
    }
}

执行 AddPeople中的main方法,入参为文件地址

执行ListPeople的main方法:


完成!

posted @ 2019-04-24 17:40  一把水果刀  阅读(714)  评论(0编辑  收藏  举报