Java调用GRPC
- 创建一个maven工程
在pom.xml引入依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--grpc版本 -->
<grpc.version>1.60.2</grpc.version>
</properties>
<dependencies>
<!-- grpc 需要的依赖-->
<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>
</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.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<!--它将{@code .proto}文件 生成java源代码 -->
<goal>compile</goal>
<!--它将{@code .proto}文件 生成grpc java源代码 -->
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<!-- 解决jar 包冲突、重复依赖、无效引用 -->
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<executions>
<execution>
<id>enforce</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireUpperBoundDeps/>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
- 新建proto文件 helloworld.proto
syntax = "proto3";
package lyj;
option java_package = "com.lyj.grpc";
option java_outer_classname = "HelloWorldServiceProto";
option java_multiple_files = true;
// 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;
}
2.进入文件目录,打开控制台
进入项目根目录所在的位置的终端,我这里是pure-design-master
E:\目录\pure-design-master>
先后输入下面命令
mvn protobuf:compile
mvn protobuf:compile-custom
成功后会在如下目录生成这六个文件
若没有生成检查命令行是否有以下提示
[INFO] E:\目录\pure-design-master\src\main\proto does not exist. Review the configuration or consider disabling the plugin.
这说明proto文件夹需要放在main下面,把位置放置正确,重新执行两条命令即可
mvn protobuf:compile
mvn protobuf:compile-custom
将上面生成的文件复制移动到下面的目录结构中,如果不存在该文件夹创建一个空的即可(放在java包下面,这里的包名与之后的server.java和client.java导入的包名对应,自己也可以根据需求更改)
3. 编写java客户端和服务端
HelloWorldClient.java
package io.grpc.examples.helloworld2;
import io.grpc.*;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.logging.Level;
public class HelloWorldClient{
private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
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) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = GreeterGrpc.newBlockingStub(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 = HelloRequest.newBuilder().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: " + response.getMessage());
}
/**
* 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 {
HelloWorldClient client = new HelloWorldClient("127.0.0.1", 50052);
try {
String user = "java_client";
if (args.length > 0) {
user = args[0];
}
client.greet(user);
} finally {
client.shutdown();
}
}
}
HelloWorldServer.java
package io.grpc.examples.helloworld2;
import io.grpc.Grpc;
import io.grpc.InsecureServerCredentials;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class HelloWorldServer {
private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
/* The port on which the server should run */
private int port = 50052;
private Server server;
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService( new GreeterImpl())
.build()
.start();
logger.info("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");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
/**
* 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 {
/** 原子Integer */
// public AtomicInteger count = new AtomicInteger(0);
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
// System.out.println("call sayHello");
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
// System.out.println(count.incrementAndGet() + Thread.currentThread().getName());
}
}
}
测试是否成功
先运行HelloWorldServer.java
输出
再运行HelloWorldClient.java
输出
以上说明java调用GRPC已经完成
python调用GRPC
- 创建proto
将java项目中的.proto文件复制到python中
打开终端,进入proto目录下输入
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./helloworld.pro
若成功,则会生成下面两个文件
- 创建服务端和客户端
server.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import grpc
from concurrent import futures
import helloworld_pb2_grpc
import helloworld_pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
print("This is server sayHello,",request,context)
return helloworld_pb2.HelloReply(message='Hello this is python server, %s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50052')
print("监听端口:50052")
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
client.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#from __future__ import print_function
import time
import grpc
import helloworld_pb2, helloworld_pb2_grpc
def run():
# NOTE(gRPC Python Team): .close() is possible on a channel and should be
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50052') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='python_client'))
print("Greeter client received: " + response.message)
time.sleep(10)
print("hi")
if __name__ == '__main__':
run()
测试是否成功
成功!
三、跨平台测试
开启python端的server
开启java端的client
或者开启java端的server和python端的client都能够互通