作者:陶玲英漂亮_607 | 来源:互联网 | 2023-07-11 18:36
1、IntellijIDEA中使用Protobuf的正确姿势一、.proto文件语法高亮显示需要安装ProtobufSupport插件依次点击Intellij中的“File”--
1、Intellij IDEA中使用Protobuf的正确姿势
一、.proto文件语法高亮显示
需要安装Protobuf Support插件
依次点击Intellij中的“File”-->"Settings"-->"Plugins"-->"Browse repositories",如下所示:
重启即可。
问题:若还是无法识别,按照下面图片配置。
二、grpc-java实践教程
1、新建一个Maven工程,添加gRPC相关依赖
io.grpcgrpc-all1.20.0
2、在POM文件中添加protocol buffers 编译插件
com.google.protobufprotobuf-java3.10.0com.google.protobufprotobuf-java-util3.10.0io.grpcgrpc-all1.11.0
kr.motd.mavenos-maven-plugin1.5.0.Final
org.xolstice.maven.pluginsprotobuf-maven-plugin0.6.1com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}grpc-javaio.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}compilecompile-custom
3 通过下面链接下载对应版本的protoc执行程序
https://github.com/protocolbuffers/protobuf/releases
4 当前项目文件结构
5 编写.proto文件
syntax = "proto3";option java_multiple_files = true;
option java_package = "com.page.awesome.dto.proto";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";//package helloworld;// The greeting service definition.
service Greeter {// Sends a greetingrpc SayHello (HelloRequest) returns (HelloReply) {}// Sends another greetingrpc SayHelloAgain (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;
}
6 现在文件目录如下
7 maven编译
注意:有两种编译方式,详情参考https://blog.csdn.net/qq_29319189/article/details/93539198
这里只选用第二种方式:
用刚才在项目里边添加的插件进行编译。
- 右击
Maven.Projects\protobuf\protobuf:compile
,选择run
,生成用于序列化的java文件。 - 再右击
Maven.Projects\protobuf\protobuf:compile-custom
,选择run
,生成用于rpc的java代码。
8 生成相应代码
9 创建HelloWorldClient和HelloWorldServer
HelloWorldClient
/** Copyright 2015 The gRPC Authors** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package com.page.awesome.hello;import com.page.awesome.dto.proto.GreeterGrpc;
import com.page.awesome.dto.proto.HelloReply;
import com.page.awesome.dto.proto.HelloRequest;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;/*** A simple client that requests a greeting from the {@link HelloWorldServer}.*/
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) {this(ManagedChannelBuilder.forAddress(host, port)// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid// needing certificates..usePlaintext().build());}/** Construct client for accessing HelloWorld server using the existing channel. */HelloWorldClient(ManagedChannel channel) {this.channel = channel;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("client request ==============" + 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("response: ===============" + 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("localhost", 50051);try {/* Access a service running on the local machine on port 50051 */String user = "world===============";if (args.length > 0) {user = args[0]; /* Use the arg as the name to greet if provided */}client.greet(user);} finally {client.shutdown();}}
}
HelloWorldServer
/** Copyright 2015 The gRPC Authors** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package com.page.awesome.hello;import com.page.awesome.dto.proto.GreeterGrpc;
import com.page.awesome.dto.proto.HelloReply;
import com.page.awesome.dto.proto.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.logging.Logger;/*** Server that manages startup/shutdown of a {@code Greeter} server.*/
public class HelloWorldServer {private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());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);Runtime.getRuntime().addShutdownHook(new Thread() {@Overridepublic 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 {@Overridepublic void sayHello(HelloRequest req, StreamObserver responseObserver) {HelloReply reply = HelloReply.newBuilder().setMessage("Hello ++++++++++++++++" + req.getName()).build();responseObserver.onNext(reply);responseObserver.onCompleted();}}
}
10 运行
先运行server,再运行client
报错:
考虑是不是版本的问题,未完待续。
注意:这里报错,但是不影响程序运行。