gRPC初试

本文详细介绍了如何使用gRPC在Java环境中搭建服务端与客户端,通过具体步骤展示了如何配置依赖、生成代码及创建自定义的服务与客户端。通过实践,读者可以深入理解gRPC的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文参照官网文档https://grpc.io/docs/tutorials/basic/java/,主要介绍gRPC的demo搭建。

我从https://github.com/grpc/grpc-java.git拷贝了grpc-java项目到本地,参考了examples文件夹下的代码,由于这个项目是gradle构建,不太熟悉gradle的我新建了一个项目并将examples下的部分代码复制到了新的项目中。

首先将examples文件夹下的pom.xml的dependencies和build拷贝到新项目中:


  <properties>
    <grpc.version>1.25.0</grpc.version><!-- CURRENT_GRPC_VERSION -->
  </properties>
  <dependencies>
    <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty</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>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.9.5</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <extensions>
      <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.4.1.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.2.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>
              <goal>compile</goal>
              <goal>compile-custom</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

然后再新项目src/main目录下新建一个proto目录,拷贝examples/src/main/proto文件夹下的helloworld.proto到新建的proto目录下,在项目中建一个helloword包,将helloworld.proto中的java_package改成自己项目中helloworld包的路径,然后执行mvn install命令。执行完成后,target目录下就会生成gRPC代码。

这个时候将examples/src/main/java/io/grpc/examples/helloworld中的类拷贝到新项目的helloworld包下。重新导入一下类,然后依次启动HelloworldServer和HelloworldClient,HelloworldClient运行 如下:

这个例子就是HelloworldClient发送一个name('world')给HelloworldServer,HelloworldServer返回给HelloworldClient消息'Hello' + name。这样,官网的Helloworld demo就运行成功了。

下面尝试仿照这个Helloworld自己写一个demo。

首先在proto目录下新建一个student.proto文件:

syntax = "proto3";

option java_multiple_files = true;
option java_package = "zhangc.grpc.student";
option java_outer_classname = "StudentProto";
option objc_class_prefix = "STU";

service StudentOperation{
    rpc Get(StudentRequest) returns (stream Student) {}
}

//定义StudentRequest类型,里面包含一个String类型的msg字段
//后面的数字是标识号 不必连续,1-15占1字节 16-2047占2字节 通常将1-15保留给常用字段
message StudentRequest{
    string msg = 1;
}
message Student{
    int32 id = 1;
    string name = 2;
}

然后执行mvn install生成gRPC代买,编写StudentServer服务端:

package zhangc.grpc.student;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 * @author zhangc
 * @version 1.0
 * @date 2019/11/28
 */
public class StudentServer {

    private final int port;
    private final Server server;

    public StudentServer(int port) throws IOException {
        this.port = port;
        this.server = ServerBuilder.forPort(port)
                .addService(new StudentService())
                .build()
                .start();
        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");
                StudentServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    public 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();
        }
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        StudentServer studentServer = new StudentServer(1214);
        studentServer.blockUntilShutdown();
    }
}

StudentClient客户端:

package zhangc.grpc.student;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @author zhangc
 * @version 1.0
 * @date 2019/11/28
 */
public class StudentClient {
    private static final Logger logger = Logger.getLogger(StudentClient.class.getName());

    private final ManagedChannel channel;
    private final StudentOperationGrpc.StudentOperationBlockingStub blockingStub;
    public StudentClient(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host, port).usePlaintext(true));
    }

    public StudentClient(ManagedChannelBuilder<?> builder) {
        channel = builder.build();
        blockingStub = StudentOperationGrpc.newBlockingStub(channel);
    }

    public void get(String msg){
        StudentRequest request = StudentRequest.newBuilder().setMsg(msg).build();
        Student student = blockingStub.get(request);
        logger.info("id:" + student.getId());
        logger.info("name:" + student.getName());
    }
    public static void main(String[] args) throws Exception {
        StudentClient client = new StudentClient("localhost", 1214);
        try {
            /* Access a service running on the local machine on port 50051 */
            String msg = "helloworld";
            if (args.length > 0) {
                msg = args[0]; /* Use the arg as the name to greet if provided */
            }
            client.get(msg);
        } finally {
            client.shutdown();
        }
    }
    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }
}

客户端发送一个msg给服务端,然后服务端将msg打印并响应一个Student对象给客户端,然后客户端将这个对象打印,运行结果如下:

server:

client:

 

 

### gRPC 介绍与使用指南 gRPC 是一种高性能、开源和通用的 RPC 框架,基于 HTTP/2 协议进行通信,并采用 Protocol Buffers(简称 Protobuf)作为接口定义语言(IDL)。它支持多种编程语言,包括但不限于 Go、Java、Python、C++ 等,广泛应用于微服务架构中[^1]。 #### gRPC 的核心概念 - **Service 定义**:通过 `.proto` 文件定义服务接口,例如 `service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} }`。`service` 关键字用于声明服务名称,`rpc` 关键字定义方法,指定输入参数和返回值类型[^4]。 - **Protobuf 消息格式**:消息结构以 `.proto` 文件的形式定义,例如: ```protobuf message HelloRequest { string name = 1; } message HelloReply { string message = 1; } ``` 上述代码中,`name` 和 `message` 分别是请求和响应中的字段,数字表示字段编号[^4]。 - **四种 RPC 类型**: - **Simple RPC**:客户端发送单个请求,服务器返回单个响应。 - **Server-side streaming RPC**:客户端发送请求后,服务器连续返回多个响应。 - **Client-side streaming RPC**:客户端连续发送多个请求,服务器返回单个响应。 - **Bidirectional streaming RPC**:客户端和服务器可以同时发送和接收流式数据[^3]。 #### gRPC 的环境搭建 在开始开发之前,需要安装必要的工具和依赖项。例如,在 Go 语言中,可以通过以下命令安装 `protoc-gen-go` 插件: ```bash go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` 如果遇到错误 `$ protoc-gen-go: program not found or is not executable`,可能是由于插件未正确安装或环境变量未配置。确保将 `$GOPATH/bin` 添加到系统路径中[^5]。 #### gRPC 的使用步骤 1. **定义 `.proto` 文件**:描述服务接口和消息结构。 2. **生成代码**:使用 `protoc` 工具生成客户端和服务端代码。例如: ```bash protoc --go_out=. --go-grpc_out=. greeter.proto ``` 3. **实现服务端逻辑**:编写服务端代码以处理 RPC 请求。例如: ```go package main import ( "context" "log" "net" "google.golang.org/grpc" pb "path/to/generated/greeter" ) type server struct{} func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello " + in.Name}, nil } func main() { lis, err := net.Listen("tcp", ":50051") if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) log.Printf("server listening at %v", lis.Addr()) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } ``` 4. **创建客户端**:编写客户端代码调用远程服务。例如: ```go package main import ( "context" "log" "time" "google.golang.org/grpc" pb "path/to/generated/greeter" ) func main() { conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "World"}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) } ``` #### gRPC 的生态系统 gRPC 可与其他工具结合使用,增强其功能: - **Envoy**:作为边缘代理,提供高级负载均衡和监控能力[^1]。 - **Jaeger**:用于全链路追踪,简化 gRPC 调用及 HTTP 请求的跟踪。 - **OpenTelemetry**:监控和指标收集框架,适用于现代微服务架构[^1]。 - **Cloud Endpoints**:Google Cloud 提供的服务网关,便于云部署和管理[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值