Kratos服务自建

Kratos服务自建

创建一个HTTP服务,第一步:创建一个liveroom这样的一个Demo项目(名字随便起,但是后面会有要修改的地方)

kratos new liveroom -d C:\项目路径 --http官网给出的命令:kratos new 项目名称 --http现在基本上kratos new 可以创建出项目,文件在GOROOT下面

生成proto文件

生成proto文件是第一步,首先要删除掉原项目下的api.bm.goapi.bp.go创建一个新的api.proto或者是修改原文件

 // 注释掉原先的service Demo新建自己的Demo,或者是直接修改(建议)

service Liveroom {
  rpc Ping(.google.protobuf.Empty) returns (.google.protobuf.Empty);
  rpc Create (Req) returns (Resp);
  rpc Delete (Req) returns (Resp);
  rpc Get (Req) returns (Resp) {
    option (google.api.http) = {
      get : "/live-room/get"
    };
  };
}

message Req{
  string name = 1 [(gogoproto.moretags)='form:"name" validata:"required"'];
}

message Resp{
  string Content = 1 [(gogoproto.jsontag)='content'];
}

go generate生成新的api.bm.goapi.pb.go文件

service/service.go

// Create
func (s *Service) Create(ctx context.Context, req *pb.Req) (reply *pb.Resp, err error) {
    reply = &pb.Resp{
        Content: "Create" + req.Name,
    }
    fmt.Printf("Create %s", req.Name)
    return
}

// Delete
func (s *Service) Delete(ctx context.Context, req *pb.Req) (reply *pb.Resp, err error) {
    reply = &pb.Resp{
        Content: "Delete" + req.Name,
    }
    fmt.Printf("Delete %s", req.Name)
    return
}

// Get
func (s *Service) Get(ctx context.Context, req *pb.Req) (reply *pb.Resp, err error) {
    reply = &pb.Resp{
        Content: "Get" + req.Name,
    }
    fmt.Printf("Get %s", req.Name)
    return
}

删掉依赖注入层的/internal/di/wire_gen.go文件,修改app.go文件之后go generate会继续生成/internal/di/wire_gen.go文件,如果你修改了.proto文件中服务的名称,你会发现有很多地方要改,比如client.go中将DemoClient改成LiveroomClient,诸如此类的地方有好几个,一步步运行,找到报错的地方,照着Demo类型改成你自己的Demo,最后注意端口冲突需要在http.tomlgrpc.toml文件中修改启动端口。

启动服务的命令:

cd kratos-demo/cmd
go build
./cmd -conf ../configs

image.png

聪明的你就会问了,为什么你的URL是酱紫的呢,在你用.proto生成文件之后,去里面找一下路由就会发现,这样一系列的坑就踩完了。基本改动的地方不多,如果就以Demo为服务名字的话,会几乎没有坑!!

猜你喜欢

转载自www.cnblogs.com/Dr-wei/p/12501359.html