server.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package grpc
  2. import (
  3. "kpt-grpc-demo/config"
  4. "kpt-grpc-demo/pkg/ops"
  5. opsPb "kpt-grpc-demo/proto/go/backend/ops"
  6. "kpt-grpc-demo/util/grpc/server"
  7. "go.uber.org/dig"
  8. "google.golang.org/grpc"
  9. "google.golang.org/grpc/reflection"
  10. )
  11. type Dependency struct {
  12. dig.In
  13. // 依赖
  14. ops.Options
  15. }
  16. type Servlet struct {
  17. server *server.Servlet
  18. Dep *Dependency
  19. opsPb.UnimplementedFieldServiceServer
  20. }
  21. // Run start run service
  22. func (s *Servlet) Run() {
  23. s.server.Run()
  24. }
  25. func (s *Servlet) Close() error {
  26. return s.server.Close()
  27. }
  28. // New Servlet impl gRPC
  29. func New(cfg *config.AppConfig, dep Dependency) *Servlet {
  30. // 允许 bangla 作为 grpc server 时,可以向客户端传输20m的数据
  31. maxSize := 20 * 1024 * 1024
  32. srv := server.New(&server.Config{
  33. ServerEnv: cfg.AppEnv,
  34. ServerName: cfg.AppName,
  35. ServerHost: cfg.GRPCServerAddr,
  36. MetricsHost: cfg.GRPCMetricsAddr,
  37. }, grpc.MaxRecvMsgSize(maxSize), grpc.MaxSendMsgSize(maxSize))
  38. servlet := &Servlet{
  39. server: srv,
  40. Dep: &dep,
  41. }
  42. opsPb.RegisterFieldServiceServer(srv.Server(), servlet)
  43. reflection.Register(srv.Server())
  44. return servlet
  45. }