接口实现
Registry 接口分为两个,Registrar 为实例注册和反注册,Discovery 为服务实例列表获取
type Registrar interface {// 注册实例Register(ctx context.Context, service *ServiceInstance) error// 反注册实例Deregister(ctx context.Context, service *ServiceInstance) error
}
type Discovery interface {// 根据 serviceName 直接拉取实例列表GetService(ctx context.Context, serviceName string) ([]*ServiceInstance, error)// 根据 serviceName 阻塞式订阅一个服务的实例列表信息Watch(ctx context.Context, serviceName string) (Watcher, error)
}
nacos的注册数据data层,在data目录选创建一个 register.go
下载包
go get github.com/nacos-group/nacos-sdk-go go get github.com/go-kratos/kratos/contrib/registry/nacos/v2go get github.com/nacos-group/nacos-sdk-go/clients/config_client
package dataimport ("github.com/go-kratos/kratos/contrib/registry/nacos/v2""github.com/go-kratos/kratos/v2/registry""github.com/nacos-group/nacos-sdk-go/clients""github.com/nacos-group/nacos-sdk-go/common/constant""github.com/nacos-group/nacos-sdk-go/vo""log"conf "xgs_kratos/gen/users"
)func CreateRegister(conf *conf.Data) registry.Registrar {sc := []constant.ServerConfig{*constant.NewServerConfig(conf.Nacos.Addr, conf.Nacos.Port),}配置项自己定义cc := constant.ClientConfig{NamespaceId: conf.Nacos.NamespaceId, // namespace idTimeoutMs: 5000, //配置项自己定义NotLoadCacheAtStart: true,LogDir: "tmp/nacos/log",CacheDir: "tmp/nacos/cache",LogLevel: "debug",}// a more graceful way to create naming clientclient, err := clients.NewNamingClient(vo.NacosClientParam{ClientConfig: &cc,ServerConfigs: sc,},)if err != nil {log.Panic(err)}r := nacos.New(client)return r
}
配置文件需要修改
api/user/conf.proto
syntax = "proto3";
package kratos.api;option go_package = "xgs_kratos/app/users/internal/conf;conf";import "google/protobuf/duration.proto";message Bootstrap {Server server = 1;Data data = 2;
}message Server {message HTTP {string network = 1;string addr = 2;google.protobuf.Duration timeout = 3;}message GRPC {string network = 1;string addr = 2;google.protobuf.Duration timeout = 3;}HTTP http = 1;GRPC grpc = 2;
}message Data {message Database {string driver = 1;string source = 2;}message Redis {string network = 1;string addr = 2;google.protobuf.Duration read_timeout = 3;google.protobuf.Duration write_timeout = 4;}
//新增nacos的配置message Nacos{string addr = 1;uint64 port = 2;string namespaceId = 3;}Database database = 1;Redis redis = 2;Nacos nacos = 3;
}
然后执行 buf generate
在app/users/connfigs里面写入配置
server:http:addr: 0.0.0.0:8000timeout: 1sgrpc:addr: 0.0.0.0:9000timeout: 1s
data:database:driver: mysqlsource: root:root@tcp(127.0.0.1:3306)/test?parseTime=True&loc=Localredis:addr: 127.0.0.1:6379read_timeout: 0.2swrite_timeout: 0.2snacos:addr: 127.0.0.1port: 8848namespaceId: local
由于使用的是模版默认的需要替换一下 app/users下 xgs_kratos/app/users/internal/conf替换成 xgs_kratos/gen/users
main.go中修改
package mainimport ("flag""github.com/go-kratos/kratos/v2/registry""os""xgs_kratos/gen/users""github.com/go-kratos/kratos/v2""github.com/go-kratos/kratos/v2/config""github.com/go-kratos/kratos/v2/config/file""github.com/go-kratos/kratos/v2/log""github.com/go-kratos/kratos/v2/middleware/tracing""github.com/go-kratos/kratos/v2/transport/grpc""github.com/go-kratos/kratos/v2/transport/http"_ "go.uber.org/automaxprocs"
)// go build -ldflags "-X main.Version=x.y.z"
var (// Name is the name of the compiled software.Name string = "users-xgs"// Version is the version of the compiled software.Version string = "v1.0.0"// flagconf is the config flag.flagconf stringid, _ = os.Hostname()
)func init() {flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml")
}func newApp(rg registry.Registrar, logger log.Logger, gs *grpc.Server, hs *http.Server) *kratos.App {return kratos.New(kratos.ID(id),kratos.Name(Name),kratos.Version(Version),kratos.Metadata(map[string]string{}),kratos.Logger(logger),kratos.Registrar(rg),kratos.Server(gs,hs,),)
}func main() {flag.Parse()logger := log.With(log.NewStdLogger(os.Stdout),"ts", log.DefaultTimestamp,"caller", log.DefaultCaller,"service.id", id,"service.name", Name,"service.version", Version,"trace.id", tracing.TraceID(),"span.id", tracing.SpanID(),)c := config.New(config.WithSource(file.NewSource(flagconf),),)defer c.Close()if err := c.Load(); err != nil {panic(err)}var bc conf.Bootstrapif err := c.Scan(&bc); err != nil {panic(err)}app, cleanup, err := wireApp(bc.Server, bc.Data, logger)if err != nil {panic(err)}defer cleanup()// start and wait for stop signalif err := app.Run(); err != nil {panic(err)}
}
修改完代码之后需要生成一下依赖 在app/users下执行 wire
然后直接执行 kratos run
nacos上报成功!!