这里我们演示一个通过 gRPC 获取数据库版本的案例。
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
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}
}
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
}
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
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
$ 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