server.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "os"
  8. "sync"
  9. "time"
  10. "github.com/tal-tech/go-zero/core/conf"
  11. "github.com/tal-tech/go-zero/example/rpc/remote/unary"
  12. "github.com/tal-tech/go-zero/zrpc"
  13. "google.golang.org/grpc"
  14. )
  15. var configFile = flag.String("f", "etc/config.json", "the config file")
  16. type GreetServer struct {
  17. lock sync.Mutex
  18. alive bool
  19. downTime time.Time
  20. }
  21. func NewGreetServer() *GreetServer {
  22. return &GreetServer{
  23. alive: true,
  24. }
  25. }
  26. func (gs *GreetServer) Greet(ctx context.Context, req *unary.Request) (*unary.Response, error) {
  27. fmt.Println("=>", req)
  28. hostname, err := os.Hostname()
  29. if err != nil {
  30. return nil, err
  31. }
  32. return &unary.Response{
  33. Greet: "hello from " + hostname,
  34. }, nil
  35. }
  36. func main() {
  37. flag.Parse()
  38. var c zrpc.RpcServerConf
  39. conf.MustLoad(*configFile, &c)
  40. server := zrpc.MustNewServer(c, func(grpcServer *grpc.Server) {
  41. unary.RegisterGreeterServer(grpcServer, NewGreetServer())
  42. })
  43. interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  44. st := time.Now()
  45. resp, err = handler(ctx, req)
  46. log.Printf("method: %s time: %v\n", info.FullMethod, time.Since(st))
  47. return resp, err
  48. }
  49. server.AddUnaryInterceptors(interceptor)
  50. server.Start()
  51. }