开发第一个gPRC的开发

在这里插入图片描述

🌷🍁 博主猫头虎 带您 Go to New World.✨🍁
🦄 博客首页——猫头虎的博客🎐
🐳《面试题大全专栏》 文章图文并茂🦕生动形象🦖简单易学!欢迎大家来踩踩~🌺
🌊 《IDEA开发秘籍专栏》学会IDEA常用操作,工作效率翻倍~💐
🌊 《100天精通Golang(基础入门篇)》学会Golang语言,畅玩云原生,走遍大小厂~💐

🪁🍁 希望本文能够给您带来一定的帮助🌸文章粗浅,敬请批评指正!🍁🐥

在这里插入图片描述

第一个gPRC的开发

在本篇博客中,我们将探讨如何使用gRPC进行开发。gRPC是一个高性能、开源和通用的RPC框架,Google开发。我们将通过以下几个部分来详细了解其开发流程:

摘要
本文详细介绍了使用gRPC进行开发的全过程,从项目结构的设计、API模块的创建、服务端和客户端模块的开发,到注意事项的总结,为读者提供了一个全面的gRPC开发指南。

导语
随着微服务架构的流行,远程过程调用(RPC)技术如gRPC越来越受到开发者的青睐。本文将为您展示如何从零开始,一步步开发一个gRPC应用。

引言
在分布式系统的世界中,服务之间的通信是至关重要的。gRPC,作为一个高性能、开源和通用的RPC框架,为此提供了强大的支持。那么,如何使用gRPC进行开发呢?让我们一探究竟。

1. 项目结构

  • xxxx-api 模块

    1. 定义 protobuf idl语言
    2. 并且通过命令创建对应的代码
    3. service
  • xxxx-server模块

    1. 实现api模块中定义的服务接口
    2. 发布gRPC服务 (创建服务端程序)
  • xxxx-client模块

    1. 创建服务端stub(代理)
    2. 基于代理(stub) RPC调用。

2. api模块

  • .proto文件 书写protobuf的IDL
  • [了解]protoc命令 把proto文件中的IDL 转换成编程语言
    protoc --java_out=/xxx/xxx  /xxx/xxx/xx.proto
    
  • [实战] maven插件 进行protobuf IDL文件的编译,并把他放置IDEA具体位置。

pom.xml中,我们需要添加以下依赖和插件:

pom.xml
 <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.52.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.52.1</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.52.1</version>
        </dependency>
        <dependency> <!-- necessary for Java 9+ -->
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency>
 </dependencies>

<build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.7.1</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:3.21.7:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.52.1:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

此外,我们还有一个示意图,但由于这是文本格式,无法直接展示。请参考您的资源路径查看:./RPC-Day1/image-20230308132952661.png

在这里插入图片描述

3. xxxx-server 服务端模块的开发

在服务端,我们首先需要实现业务接口,并添加具体的功能。以下是一个简单的Java示例:

1. 实现业务接口 添加具体的功能 (MyBatis+MySQL)
   public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {
    /*
      1. 接受client提交的参数  request.getParameter()
      2. 业务处理 service+dao 调用对应的业务功能。
      3. 提供返回值
     */
    @Override
    public void hello(HelloProto.HelloRequest request, StreamObserver<HelloProto.HelloResponse> responseObserver) {
        //1.接受client的请求参数
        String name = request.getName();
        //2.业务处理
        System.out.println("name parameter "+name);
        //3.封装响应
        //3.1 创建相应对象的构造者
        HelloProto.HelloResponse.Builder builder = HelloProto.HelloResponse.newBuilder();
        //3.2 填充数据
        builder.setResult("hello method invoke ok");
        //3.3 封装响应
        HelloProto.HelloResponse helloResponse = builder.build();

        responseObserver.onNext(helloResponse);
        responseObserver.onCompleted();;
    }
}
2. 创建服务端 (Netty)
public class GprcServer1 {
    public static void main(String[] args) throws IOException, InterruptedException {
        //1. 绑定端口 
        ServerBuilder serverBuilder = ServerBuilder.forPort(9000);
        //2. 发布服务
        serverBuilder.addService(new HelloServiceImpl());
        //serverBuilder.addService(new UserServiceImpl());
        //3. 创建服务对象
        Server server = serverBuilder.build();
        
        server.start();
        server.awaitTermination();;
    }
}

4. xxx-client 模块

客户端通过代理对象完成远端对象的调用。以下是一个简单的Java示例:


1. client通过代理对象完成远端对象的调用

public class GprcClient1 {
    public static void main(String[] args) {
        //1 创建通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        //2 获得代理对象 stub
        try {
            HelloServiceGrpc.HelloServiceBlockingStub helloService = HelloServiceGrpc.newBlockingStub(managedChannel);
            //3. 完成RPC调用
            //3.1 准备参数
            HelloProto.HelloRequest.Builder builder = HelloProto.HelloRequest.newBuilder();
            builder.setName("sunshuai");
            HelloProto.HelloRequest helloRequest = builder.build();
            //3.1 进行功能rpc调用,获取相应的内容
            HelloProto.HelloResponse helloResponse = helloService.hello(helloRequest);
            String result = helloResponse.getResult();
            System.out.println("result = " + result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            managedChannel.shutdown();
        }
    }
}

5. 注意事项

在gRPC中,处理返回值是非常重要的。以下是一些关键的注意事项:

服务端 处理返回值时
responseObserver.onNext(helloResponse1);  //通过这个方法 把响应的消息 回传client
responseObserver.onCompleted();           //通知client 整个服务结束。底层返回标记 
                                          // client就会监听标记 【grpc做的】
                                          
requestObserver.onNext(helloRequest1);
requestObserver.onCompleted();

总之,gRPC提供了一个强大的框架,使得跨语言和跨平台的通信变得简单和高效。希望这篇博客能帮助您入门gRPC的开发!

总结

gRPC不仅提供了一种高效的跨语言通信方式,还有丰富的生态系统和工具支持。通过本文的指导,我们了解了gRPC开发的各个环节,从项目结构的搭建到具体的代码实现。希望这些内容能帮助您更加轻松地入门gRPC,为您的分布式应用带来更多的可能性。

参考资料

  1. gRPC官方文档: https://grpc.io/docs/
  2. Protocol Buffers官方文档: https://developers.google.com/protocol-buffers
  3. Maven中央仓库: https://search.maven.org/
  4. gRPC Java GitHub仓库: https://github.com/grpc/grpc-java

在这里插入图片描述

原创声明

======= ·

  • 原创作者: 猫头虎

作者wx: [ libin9iOak ]

学习复习

本文为原创文章,版权归作者所有。未经许可,禁止转载、复制或引用。

作者保证信息真实可靠,但不对准确性和完整性承担责任

未经许可,禁止商业用途。

如有疑问或建议,请联系作者。

感谢您的支持与尊重。

点击下方名片,加入IT技术核心学习团队。一起探索科技的未来,共同成长。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

猫头虎

一分也是爱,打赏博主成就未来!

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

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

打赏作者

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

抵扣说明:

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

余额充值