client.go 899 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "time"
  7. "zero/core/discov"
  8. "zero/example/rpc/remote/unary"
  9. "zero/rpcx"
  10. )
  11. const timeFormat = "15:04:05"
  12. func main() {
  13. flag.Parse()
  14. client := rpcx.MustNewClient(rpcx.RpcClientConf{
  15. Etcd: discov.EtcdConf{
  16. Hosts: []string{"localhost:2379"},
  17. Key: "rpcx",
  18. },
  19. })
  20. ticker := time.NewTicker(time.Second)
  21. defer ticker.Stop()
  22. for {
  23. select {
  24. case <-ticker.C:
  25. conn, ok := client.Next()
  26. if !ok {
  27. time.Sleep(time.Second)
  28. break
  29. }
  30. greet := unary.NewGreeterClient(conn)
  31. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  32. resp, err := greet.Greet(ctx, &unary.Request{
  33. Name: "kevin",
  34. })
  35. if err != nil {
  36. fmt.Printf("%s X %s\n", time.Now().Format(timeFormat), err.Error())
  37. } else {
  38. fmt.Printf("%s => %s\n", time.Now().Format(timeFormat), resp.Greet)
  39. }
  40. cancel()
  41. }
  42. }
  43. }