grpc服务

  1. import (
  2. "github.com/yoyofx/yoyogo/abstractions"
  3. "github.com/yoyofxteam/dependencyinjection"
  4. yrpc "github.com/yoyofx/yoyogo/grpc"
  5. "google.golang.org/grpc"
  6. pb "grpc-demo/proto/helloworld"
  7. "grpc-demo/services"
  8. )
  9. func main() {
  10. configuration := abstractions.NewConfigurationBuilder().
  11. AddEnvironment().
  12. AddYamlFile("config").Build()
  13. hosting := yrpc.NewHostBuilder().
  14. UseConfiguration(configuration).Configure(func(app *yrpc.ApplicationBuilder) {
  15. //app.AddUnaryServerInterceptor( logger.UnaryServerInterceptor() )
  16. //app.AddStreamServerInterceptor( logger.StreamServerInterceptor() )
  17. app.AddGrpcService(func( server *grpc.Server, ctx *yrpc.ServiceContext ) {
  18. pb.RegisterGreeterServer( server, services.NewGreeterServer() )
  19. })
  20. }).
  21. ConfigureServices(func(collection *dependencyinjection.ServiceCollection) {
  22. //grpc client
  23. hosting.AddHostService(collection, NewClientService)
  24. collection.AddSingleton(NewHelloworldApi)
  25. //服务注册、发现
  26. nacos.UseServiceDiscovery(collection)
  27. }).Build()
  28. hosting.Run()
  29. }
  30. type Api struct {
  31. client pb.GreeterClient
  32. }
  33. // nacos 服务发现 grpc://public/[yoyogo_grpc_dev]
  34. func NewHelloworldApi(factory *grpconn.Factory) *Api {
  35. clientConn, err := factory.CreateClientConn("grpc://public/[yoyogo_grpc_dev]")
  36. if err != nil {
  37. log.Println(err)
  38. return nil
  39. }
  40. client := pb.NewGreeterClient(clientConn)
  41. return &Api{client: client}
  42. }
  43. func (hw *Api) SayHello() error {
  44. resp, _ := hw.client.SayHello(context.Background(), &pb.HelloRequest{Name: "eddycjy"})
  45. log.Printf("client.SayHello resp: %s", resp.Message)
  46. return nil
  47. }

protoc 安装

  1. wget https://github.com/google/protobuf/releases/download/v3.15.6/protobuf-all-3.15.6.zip
  2. unzip protobuf-all-3.15.6.zip && cd protobuf-3.15.6/
  3. ./configure
  4. make
  5. make install
  6. protoc --version

go插件

  1. go get -u github.com/golang/protobuf/protoc-gen-go@v1.3.2

安装grpc依赖

  1. go get -u google.golang.org/grpc@v1.29.1

.proto 代码生成

  1. protoc --go_out=plugins=grpc:. ./proto/*.proto

java 代码生成

  1. protoc --java_out=./ XX.proto

grpc调试

  1. go install github.com/fullstorydev/grpcurl/cmd/grpcurl
  1. grpcurl -plaintext localhost:31127 list
  2. # helloworld.Greeter
  1. grpcurl -plaintext localhost:31127 list helloworld.Greeter
  2. #helloworld.Greeter.SayHello
  3. #helloworld.Greeter.SayList
  4. #helloworld.Greeter.SayRecord
  5. #helloworld.Greeter.SayRoute

grpc调用

  1. grpcurl -plaintext -d '{"name":"Go"}' localhost:31127 helloworld.Greeter.SayHello
  2. #{
  3. # "message": "hello.world.at.server: Go"
  4. #}