grpc_client.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package grpc_client
  2. import (
  3. "context"
  4. "git.sxidc.com/service-supports/ds-sdk/grpc_client/v1"
  5. "google.golang.org/grpc"
  6. "google.golang.org/grpc/credentials/insecure"
  7. "time"
  8. )
  9. type Client struct {
  10. conn *grpc.ClientConn
  11. sqlServiceV1 v1.SqlServiceClient
  12. timeout time.Duration
  13. }
  14. func NewClient(address string, timeout time.Duration) (*Client, error) {
  15. conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
  16. if err != nil {
  17. return nil, err
  18. }
  19. return &Client{
  20. conn: conn,
  21. sqlServiceV1: v1.NewSqlServiceClient(conn),
  22. timeout: timeout,
  23. }, nil
  24. }
  25. func Destroy(c *Client) error {
  26. if c == nil {
  27. return nil
  28. }
  29. err := c.conn.Close()
  30. if err != nil {
  31. return err
  32. }
  33. c.sqlServiceV1 = nil
  34. c.conn = nil
  35. c = nil
  36. return nil
  37. }
  38. func (c *Client) Transaction() (v1.SqlService_TransactionClient, error) {
  39. var ctx context.Context
  40. if c.timeout == 0 {
  41. ctx = context.Background()
  42. } else {
  43. timeoutCtx, cancel := context.WithTimeout(context.Background(), c.timeout)
  44. defer cancel()
  45. ctx = timeoutCtx
  46. }
  47. return c.sqlServiceV1.Transaction(ctx)
  48. }