Java使用grpc

1、pom.xml设置

引入相关依赖

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.57.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.57.2</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.57.2</version>
        </dependency>

新增protobuf打包

 <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.22.3:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.57.2:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        &l
### gRPC Java客户端调用Go服务器端示例 为了实现Java应用程序与Go编写的gRPC服务之间的交互,需遵循特定流程来设置环境并编写相应代码。 #### 准备工作 定义协议缓冲区文件`helloworld.proto`用于描述服务接口和消息结构。此文件会被两种语言所共享以便于通信的一致性[^3]。 ```protobuf syntax = "proto3"; package helloworld; // 定义Greeter服务及其方法 service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloRequest { string name = 1; } message HelloReply { string message = 1; } ``` #### Go服务端配置 在Go环境中安装必要的依赖库,并利用上述`.proto`文件生成对应的Go源码: ```bash go get google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest protoc --go_out=. --go_opt=paths=source_relative \ --go-grpc_out=. --go-grpc_opt=paths=source_relative \ helloworld/helloworld.proto ``` 接着创建一个简单的Go程序作为gRPC的服务提供者,在其中注册处理函数以响应来自客户端的消息请求。 ```go package main import ( "context" pb "path/to/generated/go/proto" "google.golang.org/grpc" ) type server struct{} func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + req.Name}, nil } func main() { lis := ... srv := grpc.NewServer() pb.RegisterGreeterServer(srv, &server{}) if err := srv.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } ``` #### Java客户端开发 对于Java应用来说,则要依据相同的`.proto`文件生成Java类,并构建起能够发起远程过程调用的对象实例。 ```java public class HelloWorldClient { private final ManagedChannel channel; private final GreeterGrpc.GreeterBlockingStub blockingStub; public static void main(String[] args) throws Exception { HelloWorldClient client = new HelloWorldClient(); try { String user = "world"; HelloRequest request = HelloRequest.newBuilder().setName(user).build(); // 构造请求对象 HelloReply response = client.blockingStub.sayHello(request); // 发送请求给Go服务端 System.out.println(response.getMessage()); } finally { client.shutdown(); } } /** Construct client connecting to HelloWorld server at {@code host:port}. */ public HelloWorldClient() { this(ManagedChannelBuilder.forAddress("localhost", PORT) .usePlaintext()); // 创建通道时不启用TLS加密传输 } /** * Create a communication channel with the given options. * * @param builder Channel configuration parameters */ public HelloWorldClient(ChannelBuilder builder) { channel = builder.build(); blockingStub = GreeterGrpc.newBlockingStub(channel); } /** Clean up resources used by the channel. */ public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } } ``` 以上展示了如何基于同一套`.proto`定义分别搭建Go服务端以及Java客户端的具体操作指南。值得注意的是,实际项目中可能还需要考虑更多细节问题如错误处理机制、性能优化措施等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值