gRPC使用案例-使用gRPC获取数据库版本

2023-12-25 22:05:01

gRPC使用案例-使用gRPC获取数据库版本

这里我们演示一个通过 gRPC 获取数据库版本的案例。

1、新建proto

syntax = "proto3";
package pb;
import "google/protobuf/empty.proto";

service DataBase {
    rpc GetDataBaseVersion(google.protobuf.Empty) returns(VersionResponse) {}
}

message VersionResponse {
    string version = 1;
}

编译:

$ protoc --gogo_out=plugins=grpc:./ database.proto

2、新建数据库连接

package model

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

type TpOrm struct {
	*gorm.DB
}

var TpDB TpOrm

func InitTpOrm() {
	dsn := "root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Println(err)
		return
	}
	TpDB = TpOrm{db}
}

3、gRPC实现GetDataBaseVersion方法

package impl

import (
	"context"
	"github.com/golang/protobuf/ptypes/empty"
	"proj/model"
	pb "proj/proto"
)

type DataBaseServerImpl struct {
}

func (dataBaseServerImpl *DataBaseServerImpl) GetDataBaseVersion(ctx context.Context, req *empty.Empty) (rep *pb.VersionResponse, err error) {
	var version string
	rep = &pb.VersionResponse{}
	rows, err := model.TpDB.Raw("select version() as version").Rows()
	if err != nil {
		rep.Version = ""
	}
	defer rows.Close()
	for rows.Next() {
		err := rows.Scan(&version)
		if err != nil {
			rep.Version = ""
		}else{
			rep.Version = version
		}
	}
	return
}

4、Server端实现

package main

import (
	"google.golang.org/grpc"
	"log"
	"net"
	impl "proj/grpc"
	"proj/model"
	pb "proj/proto"
)

func main() {
	model.InitTpOrm()
	gRpcListen, err := net.Listen("tcp", ":23352")
	if err != nil {
		log.Printf("failed grpc listen: %v", err)
	}
	gRpcServer := grpc.NewServer()
	pb.RegisterDataBaseServer(gRpcServer, &impl.DataBaseServerImpl{})
	err = gRpcServer.Serve(gRpcListen)
	if err != nil {
		log.Println("GrpcServer fail start :%v", err.Error())
	} else {
		log.Println("GrpcServer success start %s", ":8090")
	}
}

启动:

$ go run server/server.go

5、客户端实现

package main

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/types/known/emptypb"
	"log"
	pb "proj/proto"
)

func main() {
	ctx := context.Background()
	conn, err := grpc.DialContext(ctx, "127.0.0.1:23352", grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		log.Println(err)
	}
	client := pb.NewDataBaseClient(conn)
	in := new(emptypb.Empty)
	rep, err := client.GetDataBaseVersion(ctx, in)
	if err != nil {
		log.Println(err)
	} else {
		log.Println(rep.Version)
	}
}

启动:

$ go run client/client.go
2023/06/28 17:30:37 5.5.28

6、项目的结构

$ tree go-grpc/
go-grpc/
├── client
│   └── client.go
├── go.mod
├── go.sum
├── grpc
│   └── impl.go
├── model
│   └── init.go
├── proto
│   ├── database.pb.go
│   └── database.proto
├── readme.md
├── server
│   └── server.go
└── test
    └── main.go

6 directories, 10 files

文章来源:https://blog.csdn.net/qq_30614345/article/details/133427642
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。