cmd引入控制器
和单体服务一样,微服务也需要在cmd
中引入。不同的是,启动服务由HTTP
变成了gRPC
。
app/user/internal/cmd/cmd.go
package cmd
import (
"context"
"github.com/gogf/gf/contrib/rpc/grpcx/v2"
"github.com/gogf/gf/v2/os/gcmd"
"google.golang.org/grpc"
"proxima/app/user/internal/controller/account"
)
var (
Main = gcmd.Command{
Name: "main",
Usage: "main",
Brief: "user grpc service",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
c := grpcx.Server.NewConfig()
c.Options = append(c.Options, []grpc.ServerOption{
grpcx.Server.ChainUnary(
grpcx.Server.UnaryValidate,
)}...,
)
s := grpcx.Server.New(c)
account.Register(s)
s.Run()
return nil
},
}
)
主入口文件
在入库文件内引入数据库驱动和cmd
。
app/user/main.go
package main
import (
_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
"github.com/gogf/gf/v2/os/gctx"
"proxima/app/user/internal/cmd"
)
func main() {
cmd.Main.Run(gctx.GetInitCtx())
}
配置文件
app/user/manifest/config/config.yaml
grpc:
name: "user"
address: ":32001"
database:
default:
link: "mysql:root:12345678@tcp(srv.com:3306)/user"
debug: true
gprc
字段定义了两个字段,微服务名称和监听端口。微服务名称会用作服务注册,监听端口不必多言。这两个是必要的,其他的配置见配置模板。
启动运行
切换到根目录,确保所有的依赖正常。
$ cd ../../
go mod tidy
回到微服务仓库,正式运行用户微服务。
$ cd app/user
gf run .\main.go
build: .\main.go
go build -o .\main.exe .\main.go
.\main.exe
build running pid: 15480
2024-12-06 15:02:01.246 [DEBU] {d8e6fef56e840e1815d0325bc73eda8f} set default registry using file registry as no custom registry set, path: C:\Users\half\AppData\Local\Temp\gsvc
2024-12-06 15:02:01.269 [DEBU] {d8e6fef56e840e1815d0325bc73eda8f} service register: &{Head: Deployment: Namespace: Name:user Version: Endpoints:192.168.10.91:32001 Metadata:map[protocol:grpc]}
2024-12-06 15:02:01.270 [INFO] {d8e6fef56e840e1815d0325bc73eda8f} pid[15480]: grpc server started listening on [:32001]
至此,比邻英语本的第一个微服务开发完成,和单体服务其实相差不大。
测试结果
在测试工具中请求
gRPC
时,需要使用proto
协议文件,请注意填写正确的依赖路径。
grpc 127.0.0.1:32001.account.v1.Account.UserRegister
{
"username": "oldme",
"password": "123456",
"email": "tyyn1022@gmail.com"
}
{
"id": 1
}
grpc 127.0.0.1:32001.account.v1.Account.UserLogin
{
"username": "oldme",
"password": "123456"
}
{
"token": "I am token"
}
grpc 127.0.0.1:32001.account.v1.Account.UserInfo
{
"token": "I am token"
}
{
"user": {
"Id": 1,
"Username": "oldme",
"Password": "123456",
"Email": "tyyn1022@gmail.com",
"CreatedAt": {
"seconds": "1733407200",
"nanos": 0
},
"UpdatedAt": {
"seconds": "1733407200",
"nanos": 0
}
}
}