github.com/godaddy-x/freego@v1.0.156/grpc_test.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/godaddy-x/freego/rpcx"
     6  	"github.com/godaddy-x/freego/rpcx/impl"
     7  	"github.com/godaddy-x/freego/rpcx/pb"
     8  	"google.golang.org/grpc"
     9  	"net/http"
    10  	_ "net/http/pprof"
    11  	"testing"
    12  )
    13  
    14  func TestConsulxRunGRPCServer(t *testing.T) {
    15  	initConsul()
    16  	go func() {
    17  		_ = http.ListenAndServe(":8848", nil)
    18  	}()
    19  	objects := []*rpcx.GRPC{
    20  		{
    21  			Address: "localhost",
    22  			Service: "PubWorker",
    23  			Tags:    []string{"ID Generator"},
    24  			AddRPC:  func(server *grpc.Server) { pb.RegisterPubWorkerServer(server, &impl.PubWorker{}) },
    25  		},
    26  	}
    27  	rpcx.RunServer("", false, objects...)
    28  }
    29  
    30  func TestConsulxCallGRPC_GenID(t *testing.T) {
    31  	initConsul()
    32  	rpcx.RunClient()
    33  	conn, err := rpcx.NewClientConn(rpcx.GRPC{Service: "PubWorker", Cache: 30})
    34  	if err != nil {
    35  		panic(err)
    36  	}
    37  	defer conn.Close()
    38  	res, err := pb.NewPubWorkerClient(conn.Value()).GenerateId(conn.Context(), &pb.GenerateIdReq{})
    39  	if err != nil {
    40  		panic(err)
    41  	}
    42  	fmt.Println("call rpc:", res)
    43  }
    44  
    45  func TestGRPCClient(t *testing.T) {
    46  	rpcx.RunClient(appConfig.AppId)
    47  	conn, err := rpcx.NewClientConn(rpcx.GRPC{Service: "PubWorker", Cache: 30})
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  	defer conn.Close()
    52  	res, err := pb.NewPubWorkerClient(conn.Value()).GenerateId(conn.Context(), &pb.GenerateIdReq{})
    53  	if err != nil {
    54  		panic(err)
    55  	}
    56  	fmt.Println("call result: ", res)
    57  }
    58  
    59  func BenchmarkGRPCClient(b *testing.B) {
    60  	rpcx.RunClient(appConfig.AppId)
    61  	b.StopTimer()
    62  	b.StartTimer()
    63  	for i := 0; i < b.N; i++ { //use b.N for looping
    64  		conn, err := rpcx.NewClientConn(rpcx.GRPC{Service: "PubWorker", Cache: 30})
    65  		if err != nil {
    66  			fmt.Println(err)
    67  			return
    68  		}
    69  		_, err = pb.NewPubWorkerClient(conn.Value()).GenerateId(conn.Context(), &pb.GenerateIdReq{})
    70  		if err != nil {
    71  			fmt.Println(err)
    72  			return
    73  		}
    74  		conn.Close()
    75  	}
    76  }