grpc-java⼊门实例
本⽂主要介绍如何在Intellij IDEA环境下,快速搭建出grpc-java的⼊门实例。这个⼊门实例是⼀个HelloWorld程序,客户端发送world到服务端,服务端接收到请求后,拼装成 Hello,world返回。
环境配置
JDK1.8
Maven 3.6
Intellij IDEA
创建⼀个Project
使⽤Maven⾃带的maven-archetype-webapp原型创建⼀个webapp项⽬,在src/main下新建对应的java和proto⽂件夹,并将java⽂件夹转换为 Source Root,项⽬结构如下图所⽰:
pom⽂件中引⼊相关依赖和插件
<dependency>
<groupId&pc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.27.2</version>
</dependency>
<dependency>
<groupId&pc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.27.2</version>
</dependency>
<dependency>
<groupId&pc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.27.2</version>
</dependency>
<build>
<finalName>grpc-java</finalName>
<extensions>
<extension>
<groupId&d.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId&lstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact&le.protobuf:protoc:3.11.0:exe:${os.detected.classifier}</protocArtifact>                    <pluginId>grpc-java</pluginId>
<pluginArtifact&pc:protoc-gen-grpc-java:1.27.2:exe:${os.detected.classifier}</pluginArtifact>                </configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
编写.proto⽂件,定义服务接⼝
在proto⽂件夹下编写⼀个helloworld.proto⽂件,内容如下:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "amples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
通过protocol buffer编译器⽣成服务端和客户端代码
选中Project,执⾏Maven Compile操作,会在target/generate-sources下⽣成对应的代码。
使⽤Java gRPC API为上⾯定义的服务接⼝编写客户端和服务端
在src/main/java⽂件夹下新建,amples.helloworld Package,并将代码放在此⽂件夹下,与helloworld.proto⽂件中指定的java_package参数对应。(如果放在其它⽂件夹下,代码要做适当调整,因为代码的引⽤位置变了)。
客户端代码
HelloWorldClient.java
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public HelloWorldClient(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid        // nee
ding certificates.
.usePlaintext()
.build());
}
/** Construct client for accessing HelloWorld server using the existing channel. */
HelloWorldClient(ManagedChannel channel) {
this.channel = channel;
blockingStub = wBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
/** Say hello to server. */
public void greet(String name) {
logger.info("Will try to greet " + name + " ...");
HelloRequest request = wBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + Message());
}
/**
* Greet server. If provided, the first element of {@code args} is the name to use in the
* greeting.
*/
public static void main(String[] args) throws Exception {
// Access a service running on the local machine on port 50051
HelloWorldClient client = new HelloWorldClient("localhost", 50051);
try {
String user = "world";
// Use the arg as the name to greet if provided
if (args.length > 0) {
user = args[0];
}
<(user);
} finally {
client.shutdown();
}
}
}
服务端代码
安卓开发实例入门HelloWorldServer.java
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 GreeterImpl())
.build()
.start();
logger.info("Server started, listening on " + port);
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
try {
HelloWorldServer.this.stop();
} catch (InterruptedException e) {
e.);
}
}
});
}
private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}
/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
/**
* Main launches the server from the command line.
*/
public static void main(String[] args) throws IOException, InterruptedException {
final HelloWorldServer server = new HelloWorldServer();
server.start();
server.blockUntilShutdown();
}
static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {      HelloReply reply = wBuilder().setMessage("Hello " + Name()).build();      Next(reply);
}
}
}
执⾏代码

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。