gRPC实现远程过程调用

创建gRPC项目

go mod init grpc-demo

在这里插入图片描述

编写proto文件

proto语法

syntax #协议类型,目前有两套协议 proto3、proto2,推荐使用proto3,必须放在proto文件的第一行
package #包名,必须第二行
service #定义这个proto文件的方法集合,类似于方法接口
message #类似于go语言的结构体,在此定义方法的接收、返回参数
returns #返回响应,结合service使用
rpc #定义方法的关键字,结合service使用

字段操作选项

optional #结合message使用,表示message字段的内容选填,可以传也可以不传
repeated #结合message使用,表示该字段接收或返回为数组

编写实例

syntax = "proto3";
option go_package = "./;helloworld";

service HelloWorldService{
   rpc SayHelloWorld(HelloRequest) returns(HelloResponse){}
}

message HelloRequest{
   string Name = 1;
}

message HelloResponse{
   string Msg = 1;
}

编译proto文件

protoc --go_out=plugins=grpc:./helloworld helloworld.proto

源码解析

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

服务端

package main

import (
	"fmt"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"grpc-test/proto/helloworld"
	"net"
)

type HelloWorldService struct{}

// 提供HelloWorldService实现SayHelloWorld接口
func (hw HelloWorldService) SayHelloWorld(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloResponse, error) {
	response := new(helloworld.HelloResponse)
	response.Msg = fmt.Sprintf("Say HelloWorld To %s", in.Name)
	return response, nil
}

func main() {
	listener, e := net.Listen("tcp", "127.0.0.1:8888")
	if e != nil {
		fmt.Println("Listen Error",e)
		return
	}

	helloworldService := &HelloWorldService{}

	// 实例化gprc Server
	server := grpc.NewServer()

	// 注册服务
	helloworld.RegisterHelloWorldServiceServer(server,helloworldService)

	// 开启服务
	server.Serve(listener);



}

客户端

package main

import (
	"fmt"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"grpc-test/proto/helloworld"
)

func main() {
	conn, e := grpc.Dial("127.0.0.1:8888", grpc.WithInsecure())
	if e != nil{
		fmt.Println("Connect Server Failed")
		return
	}

	// 关闭客户端连接
	defer conn.Close()

	//初始化客户端
	client := helloworld.NewHelloWorldServiceClient(conn)

	//调用方法
	response, e := client.SayHelloWorld(context.Background(), &helloworld.HelloRequest{Name: "张三"})

	if e != nil{
		fmt.Println("调用出错...")
		return
	}

	message := response.Msg

	fmt.Println("服务端返回:",message)


}

测试

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现gRPC Java的一元异步调用,可以按照以下步骤操作: 1. 定义.proto文件,包括服务名称和方法名称等信息。 2. 使用Protocol Buffer编译器生成Java代码。 3. 实现服务接口,该接口应该继承自proto中定义的服务接口。 4. 实现服务实现类,即服务接口的具体实现。 5. 使用gRPC框架提供的ServerBuilder创建服务端实例。 6. 启动服务端。 7. 在客户端使用gRPC框架提供的Stub对象调用远程方法。 下面是一个简单的示例代码,演示了如何实现一元异步调用: 定义.proto文件: ``` syntax = "proto3"; package com.example.grpc; option java_package = "com.example.grpc"; option java_outer_classname = "HelloWorldProto"; service HelloWorld { rpc sayHello (HelloRequest) returns (HelloResponse) {} } message HelloRequest { string name = 1; } message HelloResponse { string message = 1; } ``` 生成Java代码: 使用Protocol Buffer编译器生成Java代码,命令如下: ``` protoc --proto_path=./src/main/proto --java_out=./src/main/java ./src/main/proto/helloworld.proto ``` 实现服务接口: ``` package com.example.grpc; import io.grpc.stub.StreamObserver; public interface HelloWorldServiceGrpc { void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver); } ``` 实现服务实现类: ``` package com.example.grpc; import io.grpc.stub.StreamObserver; public class HelloWorldServiceImpl extends HelloWorldServiceGrpc.HelloWorldServiceImplBase { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { HelloResponse response = HelloResponse.newBuilder() .setMessage("Hello " + request.getName()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } ``` 创建服务端实例并启动: ``` package com.example.grpc; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.IOException; public class HelloWorldServer { private final int port; private final Server server; public HelloWorldServer(int port) { this.port = port; this.server = ServerBuilder.forPort(port) .addService(new HelloWorldServiceImpl()) .build(); } public void start() throws IOException { server.start(); System.out.println("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.err.println("*** shutting down gRPC server since JVM is shutting down"); HelloWorldServer.this.stop(); System.err.println("*** server shut down"); })); } public void stop() { if (server != null) { server.shutdown(); } } public void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination(); } } public static void main(String[] args) throws IOException, InterruptedException { HelloWorldServer server = new HelloWorldServer(50051); server.start(); server.blockUntilShutdown(); } } ``` 客户端调用: ``` package com.example.grpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class HelloWorldClient { private final ManagedChannel channel; private final HelloWorldServiceGrpc.HelloWorldServiceStub stub; public HelloWorldClient(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port) .usePlaintext() .build(); stub = HelloWorldServiceGrpc.newStub(channel); } public void sayHello(String name) throws InterruptedException { final CountDownLatch finishLatch = new CountDownLatch(1); StreamObserver<HelloResponse> responseObserver = new StreamObserver<HelloResponse>() { @Override public void onNext(HelloResponse response) { System.out.println(response.getMessage()); } @Override public void onError(Throwable throwable) { System.err.println(throwable.getMessage()); finishLatch.countDown(); } @Override public void onCompleted() { finishLatch.countDown(); } }; HelloRequest request = HelloRequest.newBuilder() .setName(name) .build(); stub.sayHello(request, responseObserver); finishLatch.await(1, TimeUnit.SECONDS); } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } public static void main(String[] args) throws InterruptedException { HelloWorldClient client = new HelloWorldClient("localhost", 50051); try { client.sayHello("World"); } finally { client.shutdown(); } } } ``` 以上代码演示了如何实现gRPC Java的一元异步调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shang443

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值