文章目录

  • 1、安装服务
  • 2、检查安装版本情况
  • 3、编写proto文件
  • 4、生成代码
  • 5、实现业务逻辑
  • 6、创建provider
  • 7、测试调用

1、安装服务

1、protoc安装
需去官网下载
protobuf
2、命令行安装protoc-gen-go和protoc-gen-go-grpc

$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

2、检查安装版本情况

protoc --version
# libprotoc 29.0protoc-gen-go --version
# protoc-gen-go v1.28.1protoc-gen-go-grpc --version
# protoc-gen-go-grpc 1.2.0

3、编写proto文件

syntax = "proto3";import "google/protobuf/descriptor.proto";
import "information.proto";
import "interfaceTest.proto";package interfaceTest;
option go_package="gopkg.inshopline.com/demo/book/api/grpc/gen/testGateway";message NodeReq{string id = 1;repeated string ids = 2;interfaceTest.baseDto baseField = 3;information.OpenAPIContext openAPIContext = 4;
}message TestDataTypeNodeListResponse{string code = 1;string message = 2;repeated interfaceTest.InterfaceDataTypeReq data = 3;
}service TestGatewayService {rpc testDataTypeNode(NodeReq) returns(TestDataTypeNodeListResponse);}

4、生成代码

#!/bin/bash# 与proto放在同一级,当前目录生成**.grpc.pb.go**.pb.go
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative interfaceTest.proto

或者
在这里插入图片描述

#!/bin/bash# gRPC二方API库相对于当前脚本的文件路径
working_directory=./grpccd $working_directory || exit 1
echo working_directory="$(pwd)"if [ ! -f "go.mod" ]; thenecho no go.mod file in "$(pwd)"exit 1
fimodule=$(grep '^module' go.mod | head -1)
module_path=${module#*"module "}
echo module_path="$module_path"cd ./proto || exit 1# package specification: https://protobuf.dev/reference/go/go-generated/#package
for f in *.proto; doif [ ! -f "$f" ]; thencontinueficmd="protoc \\--proto_path=. \\--go_out=../gen/ \\--go_opt=module=$module_path/gen \\--go-grpc_out=require_unimplemented_servers=false:../gen/ \\--go-grpc_opt=module=$module_path/gen \\$f"echo command="$cmd"eval "$cmd"
done

然后会生成2个文件
testGateway.pb.go
testGateway_grpc.pb.go

5、实现业务逻辑

实现proto中定义的方法

testGateway_grpc.pb.go中代码片段

// TestGatewayServiceServer is the server API for TestGatewayService service.
// All implementations should embed UnimplementedTestGatewayServiceServer
// for forward compatibility
type TestGatewayServiceServer interface {TestDataTypeNode(context.Context, *NodeReq) (*TestDataTypeNodeListResponse, error)
}// UnimplementedTestGatewayServiceServer should be embedded to have forward compatible implementations.
type UnimplementedTestGatewayServiceServer struct {
}

实现TestGatewayServiceServer方法

package testGatewayimport ("context""encoding/json""errors""fmt""gopkg.inshopline.com/commons/logx""gopkg.inshopline.com/demo/book/api/grpc/gen/interfaceTest""gopkg.inshopline.com/demo/book/api/grpc/gen/testGateway""time"
)var (logger                                      = logx.GetLogger("core-testGateway")_      testGateway.TestGatewayServiceServer = (*TestGatewayService)(nil)
)type TestGatewayService struct {testGateway.UnimplementedTestGatewayServiceServer
}func (t TestGatewayService) TestDataTypeNode(ctx context.Context, req *testGateway.NodeReq) (*testGateway.TestDataTypeNodeListResponse, error) {reqBody, _ := json.Marshal(req)logger.Infof(ctx, "TestDataTypeNode request body: %s", string(reqBody))result := &testGateway.TestDataTypeNodeListResponse{Code:    "0",Message: "success",Data:    []*interfaceTest.InterfaceDataTypeReq{},}resonse := &interfaceTest.InterfaceDataTypeReq{}mockRes := ""for _, reqId := range req.Ids {switch reqId {case "1":mockRes = "{\"id\":\"1\",\"dataURL\":\"1\",\"dataURI\":\"1\",\"dataUUID\":\"1\",\"dataFloat\":323.12,\"dataDouble\":434.23,\"dataString\":\"test interface\",\"dataBigDecimal\":132.23,\"dataBoolean\":true,\"dataShort\":12,\"dataChar\":\"c\",\"dataInt\":123,\"dataListStr\":[\"13\",\"设计gql\"],\"dataObject\":{\"objectId\":\"144fas\",\"objectSex\":\"男\",\"objectName\":\"黑海\"},\"dataObjectList\":[{\"objectId\":\"144fas\",\"objectSex\":\"男\",\"objectName\":\"黑海\"},{\"objectId\":\"jdisf1443\",\"objectSex\":\"女\",\"objectName\":\"闰土\"}],\"dataMap\":{\"mapKey\":\"name\",\"mapValue\":\"哈哈\"},\"dataMapList\":[{\"mapKey\":\"name\",\"mapValue\":\"哈哈\"},{\"mapKey\":\"hua\",\"mapValue\":\"heiei\"}]}"err := json.Unmarshal([]byte(mockRes), &resonse)if err != nil {logger.Errorf(ctx, "json unmarshal err: %s", err.Error())result.Code = "1"result.Message = fmt.Sprintf("json unmarshal err: %s", err.Error())break}case "2":mockRes = "{\"id\":\"2\",\"dataURL\":\"2\",\"dataURI\":\"2\",\"dataUUID\":\"2\",\"dataFloat\":0.0,\"dataDouble\":0.0,\"dataString\":\"2\",\"dataBigDecimal\":22.22,\"dataBoolean\":false,\"dataShort\":0,\"dataChar\":\"\\u0000\",\"dataInt\":0,\"dataListStr\":[\"22\",\"设计gql22\"],\"dataObject\":null,\"dataObjectList\":null,\"dataMap\":null,\"dataMapList\":[{\"mapKey\":null,\"mapValue\":null},{\"mapKey\":\"hua\",\"mapValue\":\"heiei\"}]}"err := json.Unmarshal([]byte(mockRes), &resonse)if err != nil {logger.Errorf(ctx, "json unmarshal err: %s", err.Error())result.Code = "1"result.Message = fmt.Sprintf("json unmarshal err: %s", err.Error())break}case "3":breakcase "4":return &testGateway.TestDataTypeNodeListResponse{Code:    "0",Message: "test data is []",}, nilcase "5":time.Sleep(3 * time.Second)breakcase "6":return nil, errors.New("异常测试")case "7":result.Code = "TS001"result.Message = "错误码测试"case "8":result.Code = "TS002"result.Message = "错误码测试2"}result.Data = append(result.Data, resonse)}return result, nil
}

6、创建provider


package providerimport ("context"test_gateway "demo/book/core/biz/testGateway""gopkg.inshopline.com/demo/book/api/grpc/gen/testGateway"
)// @Author: lyd
// @File: testGatewayService.go
// @Date: 2025/6/12 11:19
// @Description: 测试网关type TestGatewayProvider struct {
}var (_                  testGateway.TestGatewayServiceServer = (*TestGatewayProvider)(nil)testGatewayService                                      = &test_gateway.TestGatewayService{}
)func (T *TestGatewayProvider) TestDataTypeNode(ctx context.Context, req *testGateway.NodeReq) (*testGateway.TestDataTypeNodeListResponse, error) {return testGatewayService.TestDataTypeNode(ctx, req)
}
package providerimport ("google.golang.org/grpc""gopkg.inshopline.com/demo/book/api/grpc/gen/testGateway"
)func RegisterGrpcProvider(server *grpc.Server) {testGateway.RegisterTestGatewayServiceServer(server, &TestGatewayProvider{})
}

然后启动时注册上去就好了

7、测试调用

postman调用正常
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/bicheng/85149.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/85149.shtml
英文地址,请注明出处:http://en.pswp.cn/bicheng/85149.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++ 学习 多线程 2025年6月17日18:41:30

多线程(标准线程库 <thread>) 创建线程 #include <iostream> #include <thread>void hello() {std::cout << "Hello from thread!\n"; }int main() {// 创建线程并执行 hello() std::thread t(hello); //线程对象&#xff0c;传入可调用对…

常见的测试工具及分类

Web测试工具是保障Web应用质量的核心支撑&#xff0c;根据测试类型&#xff08;功能、性能、安全、自动化等&#xff09;和场景需求&#xff0c;可分为多个类别。以下从​​八大核心测试类型​​出发&#xff0c;梳理常见工具及其特点、适用场景&#xff1a; ​​一、功能测试工…

七牛存储sdk在springboot完美集成和应用 七牛依赖 自动化配置

文章目录 概要依赖配置属性配置类配置文件业务层控制层运行结果亮点 概要 七牛存储很便宜的&#xff0c;在使用项目的用好官方封装好的sdk&#xff0c;结合springboot去使用很方便&#xff0c;我本地用的是springoot3spring-boot-autoconfigure 依赖 <dependency><…

Java相关-链表-设计链表-力扣707

你可以选择使用单链表或者双链表&#xff0c;设计并实现自己的链表。 单链表中的节点应该具备两个属性&#xff1a;val 和 next 。val 是当前节点的值&#xff0c;next 是指向下一个节点的指针/引用。 如果是双向链表&#xff0c;则还需要属性 prev 以指示链表中的上一个节点…

C# 关于LINQ语法和类型的使用

常用语法&#xff0c;具体问题具体分析 1. Select2. SelectMany3. Where4. Take5. TakeWhile6. SkipWhile7. Join8. GroupJoin9. OrderBy10. OrderByDescending11. ThenBy12. Concat13. Zip14. Distinct15. Except16. Union17. Intersect18. Concat19. Reverse20. SequenceEqua…

华为OD-2024年E卷-小明周末爬山[200分] -- python

问题描述&#xff1a; 题目描述 周末小明准备去爬山锻炼&#xff0c;0代表平地&#xff0c;山的高度使用1到9来表示&#xff0c;小明每次爬山或下山高度只能相差k及k以内&#xff0c;每次只能上下左右一个方向上移动一格&#xff0c;小明从左上角(0,0)位置出发 输入描述 第一行…

Android:使用OkHttp

1、权限&#xff1a; <uses-permission android:name"android.permission.INTERNET" /> implementation com.squareup.okhttp3:okhttp:3.4.1 2、GET&#xff1a; new XXXTask ().execute("http://192.168.191.128:9000/xx");private class XXXTask…

Vue3+Element Plus动态表格列宽设置

在 Vue3 Element Plus 中实现动态设置表格列宽&#xff0c;可以通过以下几种方式实现&#xff1a; 方法 1&#xff1a;动态绑定 width 属性&#xff08;推荐&#xff09; vue 复制 下载 <template><el-table :data"tableData" style"width: 100%…

【JVM目前使用过的参数总结】

JVM参数总结 笔记记录 JVM-栈相关JVM-方法区(元空间)相关JVM-堆相关 JVM-栈相关 .-XX:ThreadStackSize1M -Xss1m 上面的简写形式【设置栈的大小】 JVM-方法区(元空间)相关 -XX:MaxMetaspaceSize10m 【设置最大元空间大小】 JVM-堆相关 -XX:MaxHeapSize10m -Xmx10m 上面的简写形…

AI辅助高考志愿填报-专业全景解析与报考指南

高考志愿填报&#xff0c;这可是关系到孩子未来的大事儿&#xff01;最近&#xff0c;我亲戚家的孩子也面临着这个难题&#xff0c;昨晚一个电话就跟我聊了好久&#xff0c;问我报啥专业好。说实话&#xff0c;这问题真不好回答&#xff0c;毕竟每个孩子情况不一样&#xff0c;…

Android Studio Windows安装与配置指南

Date: 2025-06-14 20:07:12 author: lijianzhan 内容简介 文章中&#xff0c;主要是为了初次接触 Android 开发的用户提供详细的关于 Android Studio 安装以及配置教程&#xff0c;涵盖环境准备、软件下载、安装配置全流程&#xff0c;重点解决路径命名、组件选择、工作空间设置…

SpringAI+DeepSeek-了解AI和大模型应用

一、认识AI 1.人工智能发展 AI&#xff0c;人工智能&#xff08;Artificial Intelligence&#xff09;&#xff0c;使机器能够像人类一样思考、学习和解决问题的技术。 AI发展至今大概可以分为三个阶段&#xff1a; 其中&#xff0c;深度学习领域的自然语言处理(Natural Lan…

IP5362至为芯支持无线充的22.5W双C口双向快充移动电源方案芯片

英集芯IP5362是一款应用于移动电源&#xff0c;充电宝&#xff0c;手机&#xff0c;平板电脑等支持无线充模式的22.5W双向快充移动电源方案SOC芯片,集成同步升降压转换器、锂电池充电管理、电池电量指示等功能。兼容全部快充协议&#xff0c;同步开关放电支持最大22.5W输出功率…

手游刚开服就被攻击怎么办?如何防御DDoS?

手游新上线时遭遇DDoS攻击是常见现象&#xff0c;可能导致服务器瘫痪、玩家流失甚至项目失败。面对突如其来的攻击&#xff0c;开发者与运营商需要迅速响应并建立长效防御机制。本文提供应急处理步骤与防御策略&#xff0c;助力游戏稳定运营。 一、手游开服遭攻击的应急响应 快…

秋招是开发算法一起准备,还是只准备一个

THE LAST TIME 昨天晚上半夜有个星球的26届的同学&#xff0c;私信问我。说目前是只准备开发还是开发算法一起准备&#xff08;两者技术知识都挺欠缺的&#xff09; 看到这里&#xff0c;肯定有很多同学会说。马上都该秋招了&#xff0c;还什么多线程开工&#xff0c;赶紧能住编…

web项目部署配置HTTPS遇到的问题解决方法

今天使用nginxtomcatssl完成了web项目的部署&#xff0c;本以为没有什么问题&#xff0c;但是在页面测试的时候又蹦出了这么一个问题&#xff0c;大致是说由于配置了HTTPS&#xff0c;但是之前的请求是通过HTTP请求的&#xff0c;所以现在被拦截&#xff0c;由于缺少某些权限信…

理解与建模弹性膜-AI云计算数值分析和代码验证

弹性膜在连接生物学理解和工程创新方面至关重要&#xff0c;因为它们能够模拟软组织力学、实现先进的细胞培养系统和促进柔性设备&#xff0c;广泛应用于软组织生物力学、细胞培养、生物膜建模和生物医学工程等领域。 ☁️AI云计算数值分析和代码验证 弹性膜在连接生物学理解和…

AI大模型竞赛升温:百度发布文心大模型4.5和X1

AI大模型&#xff0c;作为智能技术的巅峰之作&#xff0c;正逐步改变着我们的生活与工作方式。近期&#xff0c;百度在AI大模型领域的最新动向&#xff0c;无疑为这场科技竞赛再添一把火。3月16日&#xff0c;百度正式宣布发布文心大模型4.5及文心大模型X1&#xff0c;这两款大…

升级OpenSSL和OpenSSH 修复漏洞

升级OpenSSL和OpenSSH 目前版本OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017 升级到OpenSSH_9.8p1, OpenSSL 1.1.1u 30 May 2023 服务器CentOS Linux release 7.6.1810 (Core) 一、升级OpenSSL到1.1.1u 下载并编译 OpenSSL&#xff08;推荐目录 /usr/local/openssl&…

JavaSE - Object 类详细讲解

定义 是所有类的直接或者间接父类&#xff0c;是 Java 中唯一一个没有父类的类。其中所有的方法都是可以被子类继承的。 常用方法 equals方法&#xff1a; 比较两个对象引用的地址值是否相同&#xff0c;默认情况下是使用 “” 进行比较&#xff0c;但是这个方法一般会被之类…