转载

GO-Grpc微服务开发五 服务调用优化

使用连接池

func init() {
	so := sync.Once{}
	so.Do(func() {
		//初始化client
		var err error
		base := &fr_common.Base{}
		if base.GetEnv() == "prod" {
			consul_addr = fr_common.CONSUL_ADDR_PROD
			concul_token = fr_common.CONSUL_TOKEN_PROD
		} else {
			consul_addr = fr_common.CONSUL_ADDR_DEV
			concul_token = fr_common.CONSUL_TOKEN_DEV
		}
		config := consul.Config{
			Address:consul_addr,
			Token:concul_token,
		}
		client, err = consul.NewClient(&config)//非默认情况下需要设置实际的参数
		if err != nil {
			client = nil
			fmt.Printf("did not connect: %v", err.Error())
		}

		//初始化连接池
		pool = grpcp.New(func(addr string) (*grpc.ClientConn, error) {
			return grpc.Dial(
				addr,
				grpc.WithInsecure(),
			)
		})
	})
}

/**
 * 获取服务
 * @param name string 服务名称
 * @return service 服务实例
 */
func GetSrvHandel(name string) (conn *grpc.ClientConn, err error) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	service, _, err = client.Catalog().Service(name, "", nil)
	if err != nil {
		fmt.Printf("can not find services: %v", err.Error())
		return nil, err
	}
	//多服务端时遍历链接直到成功
	for _, v := range service  {
		addr := fmt.Sprintf("%s:%d", v.ServiceAddress, v.ServicePort)
		conn, err = pool.GetConn(addr)
	}
	return conn, err
}

源码: go-grpc-getway

原文  https://studygolang.com/articles/17234
正文到此结束
Loading...