定义proto
创建hello-world-proto目录,定义hello.proto
syntax = "proto3";
option go_package = "pbfs/hello";
option java_multiple_files = true;
option java_package = "com.example.grpc.hello";
option java_outer_classname = "HelloProto";
option objc_class_prefix = "HL";
package hello;
service Hello {
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloResponse {
string message = 1;
}
开发服务
创建hello-world-java目录
依赖
<properties>
<java.version>11</java.version>
<grpc.version>1.29.0</grpc.version>
<protobuf.version>3.11.0</protobuf.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
<protoSourceRoot>../hello-world-protos</protoSourceRoot>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
执行proto构建
mvn protobuf:compile
mvn protobuf:compile-custom
在target/generated-sources目录生成protobuf源码
服务端
public class HelloServer {
private Server server;
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(new HelloIml()) //这里可以添加多个模块
.build()
.start();
System.out.println("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
try {
HelloServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}
private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final HelloServer server = new HelloServer();
server.start();
server.blockUntilShutdown();
}
private static class HelloIml extends HelloGrpc.HelloImplBase{
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
// super.sayHello(request, responseObserver);
HelloResponse helloResponse=HelloResponse.newBuilder().setMessage("Hello "+request.getName()+", I'm Java grpc Server").build();
responseObserver.onNext(helloResponse);
responseObserver.onCompleted();
}
}
}
客户端
package com.example.grpc;
import com.example.grpc.hello.HelloGrpc;
import com.example.grpc.hello.HelloRequest;
import com.example.grpc.hello.HelloResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.concurrent.TimeUnit;
public class HelloClient {
//远程连接管理器,管理连接的生命周期
private final ManagedChannel channel;
private final HelloGrpc.HelloBlockingStub blockingStub;
public HelloClient(String host, int port) {
//初始化连接
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
//初始化远程服务Stub
blockingStub = HelloGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
//关闭连接
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public String sayHello(String name) {
//构造服务调用参数对象
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
//调用远程服务方法
HelloResponse response = blockingStub.sayHello(request);
//返回值
return response.getMessage();
}
public static void main(String[] args) throws InterruptedException {
HelloClient client = new HelloClient("127.0.0.1", 50051);
//服务调用
String content = client.sayHello("Java client");
//打印调用结果
System.out.println(content);
//关闭连接
client.shutdown();
}
}
引用
【1】 grpc for java