十分钟从零开始用Golang搭建微服务集群
十分钟从零开始用Golang搭建微服务集群 已预先准备了四个proto文件。每个proto文件都会生成相应的服务代码:
- comment.proto 文件定义了根据商品ID获取评论数据的RPC方法,用于生成评论RPC服务代码。
- inventory.proto 文件定义了根据商品ID获取库存数据的RPC方法,用于生成库存RPC服务代码。
- product.proto 文件定义了根据商品ID获取商品详情的RPC方法,用于生成商品RPC服务代码。
- shopgw.proto 文件定义了根据商品ID组装商品详情页所需数据的RPC方法,用于生成店铺RPC网关服务代码。
查看详细的代码生成过程:
sponge/examples/6_micro-cluster at main · zhufuyi/sponge
sponge是一个强大的代码生成工具,一个基于gin和gRPC的微服务框架。
更多关于十分钟从零开始用Golang搭建微服务集群的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于十分钟从零开始用Golang搭建微服务集群的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
使用sponge框架可以快速搭建微服务集群。以下是基于你提供的proto文件生成和部署微服务的步骤。
首先,确保已安装sponge:
go install github.com/zhufuyi/sponge/cmd/sponge@latest
生成商品服务代码:
sponge micro rpc --module-name=product --server-name=product --project-name=example --proto-file=product.proto --out=.
生成库存服务代码:
sponge micro rpc --module-name=inventory --server-name=inventory --project-name=example --proto-file=inventory.proto --out=.
生成评论服务代码:
sponge micro rpc --module-name=comment --server-name=comment --project-name=example --proto-file=comment.proto --out=.
生成网关服务代码:
sponge micro api --module-name=shopgw --server-name=shopgw --project-name=example --proto-file=shopgw.proto --out=.
每个服务都会生成完整的项目结构,包括:
internal/config:配置文件internal/dao:数据访问层internal/ecode:错误码internal/handler:gRPC处理器internal/model:数据模型internal/routers:HTTP路由internal/service:业务逻辑层
启动商品服务:
cd product
go run main.go --config=configs/product.yml
启动库存服务:
cd inventory
go run main.go --config=configs/inventory.yml
启动评论服务:
cd comment
go run main.go --config=configs/comment.yml
启动网关服务:
cd shopgw
go run main.go --config=configs/shopgw.yml
网关服务配置示例(configs/shopgw.yml):
grpcClient:
- name: "product"
host: "127.0.0.1"
port: 8282
- name: "inventory"
host: "127.0.0.1"
port: 8283
- name: "comment"
host: "127.0.0.1"
port: 8284
网关服务处理器示例(internal/handler/shopgw.go):
func (h *shopgwHandler) GetByID(ctx context.Context, req *v1.GetByIDRequest) (*v1.GetByIDReply, error) {
// 并发调用多个微服务
var wg sync.WaitGroup
var productResp *productV1.GetByIDReply
var inventoryResp *inventoryV1.GetByIDReply
var commentResp *commentV1.GetByIDReply
wg.Add(3)
go func() {
defer wg.Done()
productResp, _ = h.productClient.GetByID(ctx, &productV1.GetByIDRequest{Id: req.Id})
}()
go func() {
defer wg.Done()
inventoryResp, _ = h.inventoryClient.GetByID(ctx, &inventoryV1.GetByIDRequest{Id: req.Id})
}()
go func() {
defer wg.Done()
commentResp, _ = h.commentClient.GetByID(ctx, &commentV1.GetByIDRequest{Id: req.Id})
}()
wg.Wait()
// 组装响应数据
return &v1.GetByIDReply{
Product: convertProduct(productResp),
Inventory: convertInventory(inventoryResp),
Comment: convertComment(commentResp),
}, nil
}
服务注册发现配置(以consul为例):
registry:
type: "consul"
consul:
addr: "127.0.0.1:8500"
这样就在十分钟内搭建了一个完整的微服务集群,包含商品、库存、评论三个微服务和一个聚合网关服务。

