快速實現golang的grpc服務

文章目錄

  • 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;但是這個方法一般會被之類…