server.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "github.com/go-kit/kit/log"
  6. "github.com/longjoy/micro-go-course/section18/pb"
  7. "github.com/longjoy/micro-go-course/section18/user"
  8. "golang.org/x/time/rate"
  9. "google.golang.org/grpc"
  10. "net"
  11. "os"
  12. "time"
  13. )
  14. func main() {
  15. flag.Parse()
  16. var logger log.Logger
  17. {
  18. logger = log.NewLogfmtLogger(os.Stderr)
  19. logger = log.With(logger, "ts", log.DefaultTimestampUTC)
  20. logger = log.With(logger, "caller", log.DefaultCaller)
  21. }
  22. ctx := context.Background()
  23. // 建立 service
  24. var svc user.UserService
  25. svc = user.UserServiceImpl{}
  26. // 建立 endpoint
  27. endpoint := user.MakeUserEndpoint(svc)
  28. // 构造限流中间件
  29. ratebucket := rate.NewLimiter(rate.Every(time.Second*1), 100)
  30. endpoint = user.NewTokenBucketLimitterWithBuildIn(ratebucket)(endpoint)
  31. endpts := user.Endpoints{
  32. UserEndpoint: endpoint,
  33. }
  34. // 使用 transport 构造 UserServiceServer
  35. handler := user.NewUserServer(ctx, endpts)
  36. // 监听端口,建立 gRPC 网络服务器,注册 RPC 服务
  37. ls, _ := net.Listen("tcp", "127.0.0.1:8080")
  38. gRPCServer := grpc.NewServer()
  39. pb.RegisterUserServiceServer(gRPCServer, handler)
  40. gRPCServer.Serve(ls)
  41. }