1、准備工作
需要到github上下載相應的文件,地址https://github.com/google/protobuf/releases
protobuf有很多不同語言的版本,因為我們需要的是jar文件,所以選擇java版本下載。以下以版本3.1.0進行舉例說明。
如果是在linux64環境下編譯,可以選擇以下兩個文件,第一個相當於java發行版本的源碼文件,第二個是一個編譯好的protoc程序文件(如果想自己編譯protobuf程序文件,參考上篇文章protobuf的編譯安裝)。
- protobuf-java-3.1.0.tar.gz
- protoc-3.1.0-linux-x86_64.zip
如果選擇在windows環境下進行編譯,選擇以下兩個文件,同樣,第一個相當於java發行版本的源碼文件,第二個是一個編譯好的protoc程序文件,只不過windows下面的程序版本目前只有32位的。
- protobuf-java-3.1.0.zip
- protoc-3.1.0-win32.zip
2、編譯
1> 在linux環境下(需要提前裝好maven)
將以上兩個文件分別進行解壓,然后將解壓protoc-3.1.0-linux-x86_64.zip獲取的protoc程序文件復制到解壓文件目錄protobuf-java-3.1.0的對應位置。
注意位置相當重要,在以下兩個文件夾中

src目錄下面直接放一個protoc程序文件

java文件夾下面的core/src文件夾中也要放置一個protoc程序文件

之后,cd到上面所述java文件夾下面,直接運行以下命令即可
mvn package
會在java文件夾下面的core/target文件夾下面生成protobuf-java-3.1.0.jar文件
2> 在windows下面,與在linux中放置文件的位置相同,需要放置好protoc.exe程序文件,之后直接利用eclipse程序進行編譯即可
右鍵點擊java文件夾下面的pom.xml文件



3、其他說明
為了加快maven的編譯,可以將maven的源換成國內的
eclpse可以點擊【Window】菜單——【Preferences】——【Maven】——【User Settings】,在maven的倉儲位置.m2文件夾中添加一個settings.xml文件
linux下類似,直接在.m2文件夾中添加settings.xml文件
<settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <mirrors> <!-- mirror | Specifies a repository mirror site to use instead of a given repository. The repository that | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. | --> <mirror> <id>alimaven</id> <mirrorOf>central</mirrorOf> <name>aliyun maven</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </mirror> <mirror> <id>aliyunpublic</id> <name>aliyunpublic</name> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>public</mirrorOf> </mirror> <mirror> <id>centralmaven</id> <mirrorOf>centralmaven</mirrorOf> <name>centralmaven</name> <url>http://central.maven.org/maven2/</url> </mirror> </mirrors> <profiles> <profile> <id>default</id> <repositories> <repository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.aliyun.com/nexus/content/repositories/central/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus</id> <name>local private nexus</name> <url>http://maven.aliyun.com/nexus/content/repositories/central/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles> </settings>
里面的幾個地址相似,都可以用,可以隨便換位置,並非固定在一個地方,這里只是舉例。
