Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Use Grpc+maven to define interfaces, publish services, and invoke services

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

The project is built using maven. After executing the mvn compile command, the proto file automatically generates the java file, which depends on the relevant compilation plug-ins.

I. pom.xml configuration

4.0.0 com.test.grpcTest grpc-api 0.0.1-SNAPSHOT jar`` grpc-api UTF-8 io.grpc grpc-netty 1.0.0 io.grpc grpc-protobuf 1.0.0 io.grpc grpc-stub 1.0.0 io.grpc grpc-all 0.13.2 kr.motd.maven os-maven-plugin 1.4.1 .Final org.xolstice.maven.plugins protobuf-maven-plugin 0.5.0 com.google.protobuf:protoc:3.0.0:exe:$ {os.detected.classifier} grpc-java Io.grpc:protoc-gen-grpc-java:1.0.0:exe:$ {os.detected.classifier} compile compile-custom

II. Proto documents (IDL documents) are edited and compiled into java files

/ / specify proto3 format syntax = "proto3"; / / some settings for generating code option java_multiple_files = false;// generate option java_package = "com.test.grpcTest.grpc_api" in non-external class mode; / / package name option java_outer_classname = "Grpc"; / / outermost class name message UnaryRequest {string serviceName = 1; string methodName = 2; bytes data = 3; string request_id = 4 / / parameters are optional by default. If no value is assigned, this parameter will not appear in the API and will not default to} message UnaryResponse {string serviceName = 1; string methodName = 2; bytes data = 3; string request_id = 4;} service GrpcService {/ / one-to-one service request rpc SendUnaryRequest (UnaryRequest) returns (UnaryResponse) After editing the proto file, execute * * mvn compile** under the root directory of the project to compile. If you use maven to compile the proto file, you need to put the proto file under the / src/main/proto/ path by default. The compiled java file is under the target/generated-sources/ path. Copy the java file to the / src/main/java/ path. The project file structure is as follows:

3. Server code

Create a new directory / server under the / src/main/java/ path to store the server code.

Package com.test.grpcTest.grpc_api.server;import com.test.grpcTest.grpc_api.GrpcServiceGrpc;import com.test.grpcTest.grpc_api.UnaryRequest;import com.test.grpcTest.grpc_api.UnaryResponse;import com.google.protobuf.ByteString;import io.grpc.Server;import io.grpc.ServerBuilder;import io.grpc.stub.StreamObserver;import java.io.IOException;//Grpc server object public class GrpcServer {private int port = 50051bot racket GPC service port private Server server / / grpc server public static void main (String [] args) throws IOException,InterruptedException {final GrpcServer server = new GrpcServer (); server.start (); server.blockUntilShutdown ();} private void start () throws IOException {/ / specify the grpc server port and interface service object, and start the grpc server server = ServerBuilder.forPort (port) .addService (new GreeterImpl ()) .build (). Start () System.out.println ("service start..."); / / add downtime logic Runtime.getRuntime () .addShutdownHook (new Thread () {@ Override public void run () {System.err.println ("* shutting down gRPC server since JVM is shutting down"); GrpcServer.this.stop () System.err.println ("* * server shutdown");}} private void blockUntilShutdown () throws InterruptedException {if (server! = null) {server.awaitTermination ();}} private void stop () {if (server! = null) {server.shutdown () }} / / inner class that inherits the abstract class GrpcServiceGrpc.GrpcServiceImplBase,// and overrides the service method sendUnaryRequest private class GreeterImpl extends GrpcServiceGrpc.GrpcServiceImplBase {/ / UnaryRequest client request parameter, / / the encapsulation parameter public void sendUnaryRequest (UnaryRequest request,StreamObserver responseObserver) {ByteString message = request.getData () returned to the client by StreamObserver System.out.println ("server, serviceName:" + request.getServiceName () + "; methodName:" + request.getMethodName () + "; datas:" + new String (message.toByteArray (); UnaryResponse.Builder builder = UnaryResponse.newBuilder (); builder.setServiceName ("GrpcServiceResponse"). SetMethodName ("sendUnaryResponse"); responseObserver.onNext (builder.build ()); responseObserver.onCompleted () } server output log:

IV. Client code

Package com.test.grpcTest.grpc_api.client;import java.util.concurrent.TimeUnit;import com.test.grpcTest.grpc_api.GrpcServiceGrpc;import com.test.grpcTest.grpc_api.UnaryRequest;import com.test.grpcTest.grpc_api.UnaryResponse;import com.google.protobuf.ByteString;import io.grpc.ManagedChannel;import io.grpc.ManagedChannelBuilder;//grpc client class public class GrpcClient {private final ManagedChannel channel;// client-server communication channel private final GrpcServiceGrpc.GrpcServiceBlockingStub blockStub / blocking client stub node public GrpcClient (String host, int port) {channel = ManagedChannelBuilder.forAddress (host, port) .usePlaintext (true). Build (); / specify grpc server address and port to initialize communication channel blockStub = GrpcServiceGrpc.newBlockingStub (channel); / / initialize client stub node} public void shutdown () throws InterruptedException {channel.shutdown () .awaitTermination (5, TimeUnit.SECONDS) according to communication channel } / / client method public void sayHello (String str) {/ / encapsulates the request parameter UnaryRequest request = UnaryRequest.newBuilder () .setServiceName ("GrpcServiceRequest"). SetMethodName ("sendUnaryRequest") .setData (ByteString.copyFrom (str.getBytes () .build (); / / the client stub node calls the grpc service interface, passing the request parameter UnaryResponse response = blockStub.sendUnaryRequest (request) System.out.println ("client, serviceName:" + response.getServiceName () + "; methodName:" + response.getMethodName ());} public static void main (String [] args) throws InterruptedException {/ / initialize the grpc client object GrpcClient client = new GrpcClient ("127.0.0.1", 50051); for (int iTuno; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report