grpc xservice 使用
1. 安装(此处比较简单)
dep 包管理
配置环境变量
GOPATH/bin
GO/bin
protoc 下载并配置环境变量
2. xservice 安装
a. 预备(一些需要的依赖)
mkdir -p $GOPATH/src/golang.org/x
git clone https://github.com/golang/tools.git
go get github.com/gogo/protobuf/proto
go get github.com/golang/protobuf/protoc-gen-go/
go get github.com/pkg/errors
go install -v ./...
3. 简单代码
备注:项目使用的go package 为 github.com/rongfengliang/grpcapp
下面的目录在对应的子目录
a. 项目结构
├── grpcappdemo
├── grpcdemoclient
└── grpcdemoserver
b. grpcappdemo/app.proto
syntax = "proto3";
package donutloop.xservice.example.helloworld;
option go_package = "helloworld";
service HelloWorld {
rpc Hello(HelloReq) returns (HelloResp);
}
message HelloReq {
string subject = 1;
}
message HelloResp {
string text = 1;
}
c. generate code
protoc -I . app.proto --xservice_out=. --go_out=.
d. grpcdemoclient/main.go
package main
import (
"context"
"fmt"
"net/http"
pb "github.com/rongfengliang/grpcapp/grpcappdemo"
)
func main() {
client := pb.NewHelloWorldJSONClient("http://localhost:8080", &http.Client{})
for i := 1; i < 100000; i++ {
resp, err := client.Hello(context.Background(), &pb.HelloReq{Subject: "World"})
if err == nil {
fmt.Println(resp.Text) // prints "Hello World"
}
e. server
package main
import (
"context"
"net/http"
pb "github.com/rongfengliang/grpcapp/grpcappdemo"
)
// HelloWorldServer HelloWorldServer
type HelloWorldServer struct{}
// Hello Hello
func (s *HelloWorldServer) Hello(ctx context.Context, req *pb.HelloReq) (*pb.HelloResp, error) {
return &pb.HelloResp{Text: "Hello from rongfengliang " + req.Subject}, nil
}
// Run the implementation in a local server
func main() {
handler := pb.NewHelloWorldServer(&HelloWorldServer{}, nil)
// You can use any mux you like - NewHelloWorldServer gives you an http.Handler.
mux := http.NewServeMux()
// The generated code includes a const, <ServiceName>PathPrefix, which
// can be used to mount your service on a mux.
mux.Handle(pb.HelloWorldPathPrefix, handler)
http.ListenAndServe(":8080", mux)
}
4. 运行
cd grpcdemoserver
go run main.go
cd grpcdemoclient
go run main.go
5. 扩展(docker 构建集成)
参考项目对应的Dockerfile && docker-compose.yml
https://github.com/rongfengliang/grpcapp
5. 参考资料
https://github.com/google/protobuf/releases/tag/v3.5.1
https://github.com/donutloop/xservice
https://github.com/rongfengliang/grpcapp
https://github.com/golang/dep
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)