cmd引入控制器
app/word/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/word/internal/controller/words"
)
var (
Main = gcmd.Command{
Name: "main",
Usage: "main",
Brief: "word 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)
words.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/word/internal/cmd"
)
func main() {
cmd.Main.Run(gctx.GetInitCtx())
}
配置文件
app/user/manifest/config/config.yaml
grpc:
name: "word"
address: ":32002"
database:
default:
link: "mysql:root:12345678@tcp(srv.com:3306)/word"
debug: true
启动运行
确保依赖正常,运行单词微服务。
$ cd app/word
build: .\main.go
go build -o .\main.exe .\main.go
.\main.exe
build running pid: 2416
2024-12-09 15:10:40.546 [DEBU] {18cc6c8aa5700f18bf2deb5e3439664a} set default registry using file registry as no custom registry set, path: C:\Users\half\AppData\Local\Temp\gsvc
2024-12-09 15:10:40.566 [DEBU] {18cc6c8aa5700f18bf2deb5e3439664a} service register: &{Head: Deployment: Namespace: Name:word Version: Endpoints:192.168.10.98:32002 Metadata:map[protocol:grpc]}
2024-12-09 15:10:40.567 [INFO] {18cc6c8aa5700f18bf2deb5e3439664a} pid[2416]: grpc server started listening on [:32002]
至此,比邻英语本的第二个微服务开发完成。
测试结果
grpc 127.0.0.1:32002.words.v1.Words.Create
{
"uid": 1,
"word": "hello",
"definition": "used as a greeting when you meet somebody."
}
{
"id": 1
}
grpc 127.0.0.1:32002.words.v1.Words.Get
{
"id": 1
}
{
"words": {
"Id": 1,
"Uid": 1,
"Word": "hello",
"Definition": "used as a greeting when you meet somebody.",
"ExampleSentence": "Hello, I am oldme!",
"ChineseTranslation": "你好",
"Pronunciation": "həˈləʊ",
"CreatedAt": {
"seconds": "1733407200",
"nanos": 0
},
"UpdatedAt": {
"seconds": "1733407200",
"nanos": 0
}
}
}