1.创建项目
按照官网的教程创建order和user两个服务
https://go-zero.dev/cn/micro-service.html?h=grpc
创建好的目录结构:
├── mall
│ └── order // order服务
│ └──....
│ └── user // user服务
│ └──....
│ └── go.mod
│ └── go.sum
2.修改代码支持nacos
参考https://github.com/zeromicro/zero-contrib/tree/main/zrpc/registry/nacos
2.1 安装依赖
go get -u github.com/zeromicro/zero-contrib/zrpc/registry/nacos
2.2 修改service代码
- mall/user/rpc/user.go:
!!注意:git上的参考代码并没有写全,可以正常注册到nacos上但是服务没有提供任何接口
package main
import (
"flag"
"github.com/nacos-group/nacos-sdk-go/common/constant"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/zrpc"
"github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
_ "github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
"go-zero-test1/mall/user/rpc/internal/config"
"go-zero-test1/mall/user/rpc/internal/server"
"go-zero-test1/mall/user/rpc/internal/svc"
"go-zero-test1/mall/user/rpc/types/user"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "mall/user/rpc/etc/user.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
srv := server.NewUserServer(ctx)
serverRpc:= zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
user.RegisterUserServer(grpcServer, srv)
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
// 注册服务
sc := []constant.ServerConfig{
*constant.NewServerConfig("127.0.0.1", 8848),
}
cc := &constant.ClientConfig{
NamespaceId: "public",
TimeoutMs: 50000,
NotLoadCacheAtStart: true,
LogDir: "D:/tmp/nacos/log",
CacheDir: "D:/tmp/nacos/cache",
RotateTime: "1h",
MaxAge: 300,
LogLevel: "debug",
}
opts := nacos.NewNacosConfig("user.rpc", c.ListenOn, sc, cc)
_ = nacos.RegitserService(opts)
serverRpc.Start()
}
2.3修改client代码
- mall/order/api/order.go:
加上这句话就好了
_ "github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
完整代码:
package main
import (
"flag"
"fmt"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
_ "github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
"go-zero-test1/mall/order/api/internal/config"
"go-zero-test1/mall/order/api/internal/handler"
"go-zero-test1/mall/order/api/internal/svc"
)
var configFile = flag.String("f", "mall/order/api/etc/order.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}
- mall/order/api/etc/order.yaml:
Name: order
Host: 0.0.0.0
Port: 8888
UserRpc:
Target: nacos://127.0.0.1:8848/user.rpc?namespaceid=public&timeout=5000s
3.运行
依次运行nacos、user服务和order服务
- nacos启动命令:
.\startup.cmd -m standalone
浏览器输入
http://localhost:8888/api/order/get/1
返回
{
"id": "1",
"name": "test order"
}