grpc之golang实现服务从数据库获取数据

在前面的基础上实现数据从数据库获取返回

  1. 数据库使用的是upper库,支持mysql和mongodb
go get github.com/upper/db/v4/adapter/mysql
  1. 根目录下新建data目录,新建文件carrierData.go和settings.go

settings.go

package data

import "github.com/upper/db/v4/adapter/mysql"

var settings = mysql.ConnectionURL{
	Database: ``,         // Database name
	Host:     ``,   // Server IP or name
	User:     ``, // Username
	Password: ``,   // Password
}

type DataResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

carrierData.go

package data

import (
	"github.com/upper/db/v4"
	"github.com/upper/db/v4/adapter/mysql"
	"log"
)

type CarrierData struct {
	Id   int    `db:"id"`
	Name string `db:"name"`
}

type CarriersResponse struct {
	DataResponse
	Data []CarrierData `json:"data"`
}

func GetCarriers(page int64, pageSize int64) CarriersResponse {
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 100
	}
	carrierResponse := CarriersResponse{}
	sess, err := mysql.Open(settings)
	if err != nil {
		carrierResponse.Code = -1
		carrierResponse.Message = err.Error()
		return carrierResponse
	}
	defer sess.Close()
	collection := sess.Collection("table")
	var res db.Result
	res = collection.Find().OrderBy("id")
	p := res.Paginate(uint(pageSize))
	var carriers []CarrierData

	err = p.Page(uint(page)).All(&carriers)
	//err = res.All(&carriers)
	if err != nil {
		carrierResponse.Code = -1
		carrierResponse.Message = err.Error()
		return carrierResponse
	}
	carrierResponse.Code = 1
	carrierResponse.Message = "success"
	carrierResponse.Data = carriers
	return carrierResponse
}

func GetCarrier(name string) CarrierData {
	sess, err := mysql.Open(settings)
	if err != nil {
		log.Fatalf("db.Open(): %q\n", err)
	}
	defer sess.Close()

	q := sess.SQL().
		SelectFrom("table").
		Where("name = ?", name)
	var carrierData CarrierData
	q.One(&carrierData)
	return carrierData
}

  1. server目录下的carrier.go文件rpc方法调整
package server

import (
	"context"
	"log"
	"rpc/data"
	rca "rpc/proto/carrier"
)

var tToken Token

type Carrier struct {
	rca.UnimplementedCarrierServer
}

func (carrier *Carrier) GetCarrier(ctx context.Context, in *rca.CarrierRequest) (*rca.CarrierMsg, error) {
	// 检测Token是否有效
	if err := tToken.Check(ctx); err != nil {
		return nil, err
	}
	carrierMs := data.GetCarrier(in.Name)
	carrierMsg := &rca.CarrierMsg{}
	carrierMsg.Id = int64(carrierMs.Id)
	carrierMsg.Name = carrierMs.Name
	log.Println(carrierMsg.Name)
	return carrierMsg, nil
}

func (carrier *Carrier) GetCarriers(ctx context.Context, in *rca.CarriersRequest) (*rca.CarriersReply, error) {
	// 检测Token是否有效
	if err := tToken.Check(ctx); err != nil {
		return nil, err
	}
	carriers := data.GetCarriers(in.Page, in.PageSize)
	response := &rca.CarriersReply{}

	response.Page = in.Page
	response.PageSize = in.PageSize

	for _, carr := range carriers.Data {
		carrierMsg := &rca.CarrierMsg{}
		carrierMsg.Id = int64(carr.Id)
		carrierMsg.Name = carr.Name
		response.CarrierInfo = append(response.CarrierInfo, carrierMsg)
	}

	return response, nil
}

  1. 启动服务
go run server.go
  1. 启动客户端
package main

import (
	"context"
	"flag"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	rca "rpc/proto/carrier"
	"time"
)

type CAuth struct {
}

func (c CAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	//TODO implement me
	return map[string]string{
		"accessToken": "65794a3163325679546d46745a534936496e647463794973496e426863334e5862334a6b496a6f694d54497a4e445532496e303d",
	}, nil
}

func (c CAuth) RequireTransportSecurity() bool {
	return false
}
func main() {
	var addr = flag.String("addr", "ip:50051", "the address to connect to")
	flag.Parse()
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	opts = append(opts, grpc.WithPerRPCCredentials(new(CAuth)))
	conn, err := grpc.Dial(*addr, opts...)
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := rca.NewCarrierClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	//通过carrier名称获取carrier
	r1, err := c.GetCarrier(ctx, &rca.CarrierRequest{Name: "sdfsdfsdf"})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Carrier: %s", r1.GetName())
	r2,err := c.GetCarriers(ctx,&rca.CarriersRequest{Page:1,PageSize: 10})
	jStr, _ :=json.Marshal(r2)
	log.Println(string(jStr))
}

  1. 或者通过postman请求 image image