server.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "flag"
  6. "zero/core/conf"
  7. "zero/example/tracing/remote/portal"
  8. "zero/example/tracing/remote/user"
  9. "zero/rpcx"
  10. "google.golang.org/grpc"
  11. )
  12. var configFile = flag.String("f", "etc/config.json", "the config file")
  13. type (
  14. Config struct {
  15. rpcx.RpcServerConf
  16. UserRpc rpcx.RpcClientConf
  17. }
  18. PortalServer struct {
  19. userRpc *rpcx.RpcClient
  20. }
  21. )
  22. func NewPortalServer(client *rpcx.RpcClient) *PortalServer {
  23. return &PortalServer{
  24. userRpc: client,
  25. }
  26. }
  27. func (gs *PortalServer) Portal(ctx context.Context, req *portal.PortalRequest) (*portal.PortalResponse, error) {
  28. conn, ok := gs.userRpc.Next()
  29. if !ok {
  30. return nil, errors.New("internal error")
  31. }
  32. greet := user.NewUserClient(conn)
  33. resp, err := greet.GetGrade(ctx, &user.UserRequest{
  34. Name: req.Name,
  35. })
  36. if err != nil {
  37. return &portal.PortalResponse{
  38. Response: err.Error(),
  39. }, nil
  40. } else {
  41. return &portal.PortalResponse{
  42. Response: resp.Response,
  43. }, nil
  44. }
  45. }
  46. func main() {
  47. flag.Parse()
  48. var c Config
  49. conf.MustLoad(*configFile, &c)
  50. client := rpcx.MustNewClient(c.UserRpc)
  51. server := rpcx.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
  52. portal.RegisterPortalServer(grpcServer, NewPortalServer(client))
  53. })
  54. server.Start()
  55. }