我们知道,在集群环境节点之间进行交换的数据必须经过序列化/反序列化处理过程,而在这方面protobuf是一个比较高效、易用的模式。用户首先在.proto文件中用IDL来定义系统中各种需要进行交换的数据类型。然后用protoc编译器自动产生相关的源代码,里面包括了完整的序列化处理函数。在一个集成的系统环境内,protobuf数据必须保持与所有系统的松散耦合,不能对这些用户系统有任何依赖。这样把protobuf数据类型和相关的序列化/反序列化函数打成一个独立的包,由用户系统各自引用就是一种最佳解决方案了。
下面示范产生一个独立的protobuf包。build.sbt定义如下:
import scalapb.compiler.Version.scalapbVersion
import scalapb.compiler.Version.grpcJavaVersion
name := "common-protobuf-data"
version := "0.1"
scalaVersion := "2.12.6"
libraryDependencies ++= Seq(
"com.thesamet.scalapb" %% "scalapb-runtime" % scalapbVersion % "protobuf",
"io.grpc" % "grpc-netty" % grpcJavaVersion,
"com.thesamet.scalapb" %% "scalapb-runtime-grpc" % scalapbVersion
)
PB.targets in Compile := Seq(
scalapb.gen(
flatPackage = true
) -> (sourceDirectory in Compile).value / "scala/generated"
)
注意我们指定把产生的源代码放在src/main/scala/generated/目录下。
我们再随便建个.proto文件:
syntax = "proto3";
// Brought in from scalapb-runtime
import "scalapb/scalapb.proto";
import "google/protobuf/wrappers.proto";
package proto.microservices;
message Added {
int32 nbr1 = 1;
int32 nbr2 = 2;
}
message Subtracted {
int32 nbr1 = 1;
int32 nbr2 = 2;
}
message AddedResult {
int32 nbr1 = 1;
int32 nbr2 = 2;
int32 result = 3;
}
message SubtractedResult {
int32 nbr1 = 1;
int32 nbr2 = 2;
int32 result = 3;
}
用sbt package 产生common-protobuf-data_???.jar文件。在使用方sbt项目里可以用unmanagedBase指定.jar路径或者把包放到默认的lib/目录下:
lazy val commonSettings = Seq(
name := "using-common-protobuf-data",
version := "1.0",
scalaVersion := "2.12.6",
)
lazy val local = (project in file("."))
.settings(commonSettings)
.settings(
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-remote" % "2.5.11",
"com.thesamet.scalapb" %% "scalapb-runtime" % scalapb.compiler.Version.scalapbVersion % "protobuf"
),
)
unmanagedBase := file("/users/tiger-macpro/jars/")
PB.targets in Compile := Seq(
scalapb.gen() -> (sourceManaged in Compile).value
)
好了。在上面的.sbt文件中有关路径的设置需要总结一下:
1、改变默认源代码路径: (src/main/scala, src/test/scala)
scalaSource in Compile := baseDirectory.value / "src"
scalaSource in Test := baseDirectory.value / "test-src"
javaSource in Compile := baseDirectory.value / "src"
javaSource in Test := baseDirectory.value / "test-src"
2、改变默认资源路径:(src/main/resources)
resourceDirectory in Compile := baseDirectory.value / "resources"
resourceDirectory in Test := baseDirectory.value / "test-resources"
3、改变默认附加库路径:(lib/)
unmanagedBase := baseDirectory.value / "jars"
//只在编译时引用
unmanagedBase in Compile := baseDirectory.value / "lib" / "main"
4、取消根目录为源代码默认路径:
sourcesInBase := false
5、增加一个源代码路径:
unmanagedSourceDirectories in Compile += baseDirectory.value / "extra-src"
6、增加一个资源路径:
unmanagedResourceDirectories in Compile += baseDirectory.value / "extra-resources"