github.com/kaydxh/golang@v0.0.131/go/net/grpc/grpc_client.go (about)

     1  /*
     2   *Copyright (c) 2022, kaydxh
     3   *
     4   *Permission is hereby granted, free of charge, to any person obtaining a copy
     5   *of this software and associated documentation files (the "Software"), to deal
     6   *in the Software without restriction, including without limitation the rights
     7   *to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     8   *copies of the Software, and to permit persons to whom the Software is
     9   *furnished to do so, subject to the following conditions:
    10   *
    11   *The above copyright notice and this permission notice shall be included in all
    12   *copies or substantial portions of the Software.
    13   *
    14   *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    15   *IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    16   *FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    17   *AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    18   *LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    19   *OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    20   *SOFTWARE.
    21   */
    22  package grpc
    23  
    24  import (
    25  	"context"
    26  	"fmt"
    27  	"math"
    28  	"time"
    29  
    30  	context_ "github.com/kaydxh/golang/go/context"
    31  	interceptordebug_ "github.com/kaydxh/golang/pkg/middleware/grpc-middleware/debug"
    32  	interceptortimer_ "github.com/kaydxh/golang/pkg/middleware/grpc-middleware/timer"
    33  	"google.golang.org/grpc"
    34  )
    35  
    36  //16MB
    37  const (
    38  	defaultMaxMsgSize                      = math.MaxInt32 //16 * 1024 * 1024
    39  	defaultConnectionTimeout time.Duration = 5 * time.Second
    40  )
    41  
    42  type GrpcClient struct {
    43  	conn *grpc.ClientConn
    44  	opts struct {
    45  		maxMsgSize        int
    46  		connectionTimeout time.Duration
    47  	}
    48  }
    49  
    50  func NewGrpcClient(addr string, options ...GrpcClientOption) (*GrpcClient, error) {
    51  	c := &GrpcClient{}
    52  	c.ApplyOptions(options...)
    53  
    54  	if c.opts.maxMsgSize == 0 {
    55  		c.opts.maxMsgSize = defaultMaxMsgSize
    56  	}
    57  	if c.opts.connectionTimeout == 0 {
    58  		c.opts.connectionTimeout = defaultConnectionTimeout
    59  	}
    60  
    61  	ctx, cancel := context_.WithTimeout(context.Background(), c.opts.connectionTimeout)
    62  	defer cancel()
    63  	conn, err := grpc.DialContext(ctx, addr, ClientDialOptions()...)
    64  	if err != nil {
    65  		return nil, fmt.Errorf("failed to connect address: %v", addr)
    66  	}
    67  	c.conn = conn
    68  
    69  	return c, nil
    70  }
    71  
    72  func (g *GrpcClient) Conn() *grpc.ClientConn {
    73  	return g.conn
    74  }
    75  
    76  func (g *GrpcClient) Close() error {
    77  	if g.conn != nil {
    78  		return g.conn.Close()
    79  	}
    80  
    81  	return nil
    82  }
    83  
    84  func ClientDialOptions(disablePrintMethods ...string) []grpc.DialOption {
    85  	var opts []grpc.DialOption
    86  	opts = append(opts,
    87  		grpc.WithInsecure(),
    88  		grpc.WithDefaultCallOptions(
    89  			grpc.MaxCallRecvMsgSize(defaultMaxMsgSize),
    90  			grpc.MaxCallSendMsgSize(defaultMaxMsgSize),
    91  		),
    92  		grpc.WithInitialWindowSize(defaultMaxMsgSize),
    93  		grpc.WithInitialConnWindowSize(defaultMaxMsgSize),
    94  		grpc.WithStatsHandler(&statHandler{}),
    95  		grpc.WithChainUnaryInterceptor(
    96  			interceptortimer_.UnaryClientInterceptorOfTimer(),
    97  			interceptordebug_.UnaryClientInterceptorOfInOutputPrinter(disablePrintMethods...)),
    98  	)
    99  	return opts
   100  }
   101  
   102  func GetGrpcClientConn(
   103  	addr string,
   104  	connectionTimeout time.Duration,
   105  	disablePrintMethods ...string,
   106  ) (*grpc.ClientConn, error) {
   107  	ctx, cancel := context_.WithTimeout(context.Background(), connectionTimeout)
   108  	defer cancel()
   109  
   110  	conn, err := grpc.DialContext(ctx, addr, ClientDialOptions(disablePrintMethods...)...)
   111  	if err != nil {
   112  		return nil, fmt.Errorf("failed to connect address: %v", addr)
   113  	}
   114  
   115  	return conn, nil
   116  }