rpc_service.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * @description: rpc services 实例
  3. * @Author: CP
  4. * @Date: 2020-11-12 22:53:14
  5. * @FilePath: \construction_management\services\rpc_service.go
  6. */
  7. package services
  8. import (
  9. "context"
  10. "log"
  11. "time"
  12. safe "go.mod/proto"
  13. "google.golang.org/grpc"
  14. )
  15. type RpcService interface {
  16. Test(RpcConnect *grpc.ClientConn)
  17. }
  18. //返回service操作类
  19. type rpcService struct {
  20. // address string
  21. // defaultName string
  22. //Ctx iris.Context
  23. //rpcClient *grpc.ClientConn
  24. // 定义proto 接口文件- /proto/rpc.proto
  25. // pb.UnimplementedGreeterServer
  26. }
  27. //创建项目用户service
  28. func NewRpcService() RpcService {
  29. return &rpcService{
  30. // address: "192.168.1.26:5001",
  31. //rpcClient: GetGrpcClient(ctx),
  32. }
  33. }
  34. // func GetGrpcClient(ctx iris.Context) *grpc.ClientConn {
  35. // // // 启动grpc客户端,连接grpc服务端
  36. // // conn, err := grpc.Dial(address, grpc.WithInsecure())
  37. // // if err != nil {
  38. // // log.Fatalf("did not connect: %v", err)
  39. // // }
  40. // // // defer conn.Close()
  41. // // return conn
  42. // }
  43. // 具体的业务逻辑
  44. func (s *rpcService) Test(RpcConnect *grpc.ClientConn) {
  45. // 1.结束后关闭
  46. //defer s.rpcClient.Close()
  47. rpcClient := safe.NewGreeterClient(RpcConnect)
  48. // c := pb.NewGreeterClient(conn)
  49. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  50. defer cancel()
  51. r, err := rpcClient.SayHello(ctx, &safe.HelloRequest{Name: "caipin"})
  52. if err != nil {
  53. log.Fatalf("could not greet: %v", err)
  54. }
  55. log.Printf("Greeting: %s", r.GetMessage())
  56. }