grpc接口调用

grpc接口调用


参考博客:
Grpc项目集成到java方式调用实践
gRpc入门和springboot整合
java 中使用grpc java调用grpc服务

准备

因为需要生成代码,所以必备插件
在这里插入图片描述
安装后重启

依赖包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mistra</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.10</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <protoc.version>3.25.2</protoc.version>
        <grpc.version>1.61.1</grpc.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>${grpc.version}</version>

        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-core</artifactId>
            <version>${grpc.version}</version>

        </dependency>

        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.25.2</version> <!-- 或者与你的 protoc.version 相匹配的版本 -->
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
            <version>${grpc.version}</version>
        </dependency>
        <dependency>
            <!-- necessary for Java 9+ -->
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:${protoc.version}: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>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

在resource同级目录下创建一个包,包下创建proto文件
在这里插入图片描述
proto文件

syntax = "proto3";

package mistra;
//生成的java代码包名
option java_package = "org.example.mistra";
//创建的javaBean的文件名
option java_outer_classname = "MistraProto";
//option java_generic_services = true;
option java_multiple_files = true;

//请求
message MistraRequest {
  string id = 1;
  int64 timestamp = 2;
  string message = 3;
}

//响应
message MistraResponse {
  string message = 1;
}
//声明一个服务名称
service MistraService {
  rpc SendMessage(MistraRequest) returns (MistraResponse) {}
}


然后使用maven打包,在target目录下生成代码,复制到自己的目录下。
生成代码:
在这里插入图片描述
复制到自己目录下,再创建一个client和server,结构如下
在这里插入图片描述

client

package com.test.grpc.mistra.generate.client;

import com.test.grpc.mistra.generate.MistraRequest;
import com.test.grpc.mistra.generate.MistraResponse;
import com.test.grpc.mistra.generate.MistraServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

/**
 * @author清梦
 * @site www.xiaomage.com
 * @company xxx公司
 * @create 2024-06-04 21:59
 */
public class MistraClient {

    private final ManagedChannel channel;
    private final MistraServiceGrpc.MistraServiceBlockingStub blockingStub;


    public MistraClient(String host, int port) {
        channel = ManagedChannelBuilder.forAddress(host, port)
                .usePlaintext()
                .build();

        blockingStub = MistraServiceGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public void greet(String name) {
        MistraRequest request = MistraRequest.newBuilder().setId(name).build();
        MistraResponse response = blockingStub.sendMessage(request);
        System.out.println(response.getMessage());

    }

    public static void main(String[] args) throws InterruptedException {
        MistraClient client = new MistraClient("127.0.0.1", 8001);
        System.out.println("-------------------客户端开始访问请求-------------------");
        for (int i = 0; i < 10; i++) {
            client.greet("你若想生存,绝处也能缝生: " + i);
        }
    }
}

server

package com.test.grpc.mistra.generate.server;

import com.test.grpc.mistra.generate.MistraRequest;
import com.test.grpc.mistra.generate.MistraResponse;
import com.test.grpc.mistra.generate.MistraServiceGrpc;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

/**
 * @author清梦
 * @site www.xiaomage.com
 * @company xxx公司
 * @create 2024-06-04 21:59
 */
public class MistraServer {

    private int port;

    private Server server;

    private void start() throws IOException{
        server = ServerBuilder.forPort(port)
                .addService((BindableService) new MistraSendMessage())
                .build()
                .start();

        System.out.println("-------------------服务端服务已开启,等待客户端访问------------------");

        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                System.out.println("*** shutting down gRPC server since JVM is shutting down");
                MistraServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        final MistraServer server = new MistraServer();
        //启动服务
        server.start();
        //服务一直在线,不关闭
        server.blockUntilShutdown();
    }

    private class MistraSendMessage extends MistraServiceGrpc.MistraServiceImplBase {
        @Override
        public void sendMessage(MistraRequest request, StreamObserver<MistraResponse> responseObserver) {
            //业务实现代码
            System.out.println("server:" + request.getId());
            MistraResponse response = MistraResponse.newBuilder().setMessage("响应信息" + request.getMessage()).build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    }


}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
gRPC是一种高性能的远程过程调用框架,它可以用于构建分布式系统。通过gRPC,我们可以定义我们自己的接口服务,并通过使用Protocol Buffers来定义消息类型和服务接口接口文档是一份详细描述这些接口及其使用方法的文档。 gRPC接口文档中文提供了对于gRPC接口的详细说明和使用指南。文档中通常包含以下信息: 1. 接口定义:文档会提供接口的定义,包括接口名称、方法名称和方法参数。这些定义将在客户端和服务端之间进行通信时使用。 2. 消息类型:文档会描述消息类型及其字段的定义。这些消息类型用于在不同服务之间传递数据。 3. 错误码:文档会列出可能的错误码及其含义。这些错误码用于标识调用接口时可能出现的错误情况。 4. 使用示例:文档中通常会提供一些使用示例,以帮助开发人员理解如何使用接口。这些示例可以包括创建客户端、调用接口方法和处理返回结果。 5. 安全认证:如果接口需要进行安全认证,文档会提供相应的认证方法和配置。 通过阅读gRPC接口文档中文,开发人员可以更加清楚地了解如何使用gRPC构建分布式系统。在开发过程中,可以根据接口文档编写客户端代码、验证接口调用和处理错误情况。接口文档也可以帮助团队成员之间更加协作,确保彼此的理解和一致性。 总之,gRPC接口文档中文在使用gRPC构建分布式系统时是一个重要的参考工具。它提供了接口的详细定义、用法示例和错误处理,帮助开发人员更加高效地使用gRPC接口
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值