使用 Go 的 gRPC 读取 Redis 数据 (Read)

需要有设置文件、服务器程序和客户端程序这三者。

$ tree
.
├── redis_read
│   └── redis_read.proto
├── redis_read_client
│   └── main.go
└── redis_read_server
    └── main.go

设定文件 (shè


syntax = "proto3";

package redis_read;

service Greeter {
    rpc RedisRead (RedisRequest) returns (RedisReply) {}
}

message RedisRequest {
    string key = 1;
}

message RedisReply {
    string strjson = 1;
}

服务器程序

// ---------------------------------------------------------------
//
//  redis_read_server/main.go
//
//                  Feb/11/2020 
// ---------------------------------------------------------------
package main

import (
    "context"
    "log"
    "net"
    "fmt"
    "os"
    "strings"

    "google.golang.org/grpc"
    pb "../redis_read"
)

const (
    port = ":50051"
)

type server struct {
    pb.UnimplementedGreeterServer
}

// ---------------------------------------------------------------
func socket_read_proc (conn net.Conn,key_in string) string {
    str_received := ""
    _, err := conn.Write([]byte("get " + key_in + "\r\n"))
    if err != nil {
        fmt.Println(err)
        return str_received
        }

    buf := make([]byte, 1024)
    nn, err := conn.Read(buf[:])
    if err != nil {
        fmt.Println(err)
        return str_received
        }

    str_received = string(buf[0:nn])

    return  str_received
}

// ---------------------------------------------------------------
func redis_socket_read_proc (conn net.Conn,key_in string) string {
    json_str := ""
    str_received := socket_read_proc (conn,key_in)

    lines := strings.Split(str_received,"\n")

    if (! strings.Contains(lines[0],"END")) {
        json_str = lines[1]
        }

    return  json_str
}

// ---------------------------------------------------------------
func redis_read_proc (key_in string) string {
    str_json := ""

    hostname := "localhost"
    port := "6379"

    conn, err := net.Dial ("tcp", hostname + ":" + port)
    if err != nil {
        fmt.Println(err)
        return str_json
        }

    str_json = redis_socket_read_proc (conn,key_in)

//  str_json = key_in + " aaa " + key_in

    return str_json
}
// ---------------------------------------------------------------
func (s *server) RedisRead(ctx context.Context, in *pb.RedisRequest) (*pb.RedisReply, error) {
    fmt.Fprintf (os.Stderr,"*** check aaa ***\n")
    key := in.GetKey()
    fmt.Fprintf (os.Stderr,"key = " + key + "\n")
    str_json := redis_read_proc (key)
    return &pb.RedisReply{Strjson: str_json }, nil
}

// ---------------------------------------------------------------
func main() {
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

// ---------------------------------------------------------------

客户端程序

// ---------------------------------------------------------------
//
//  redis_read_client/main.go
//
//                  Feb/11/2020
//
// ---------------------------------------------------------------
package main

import (
    "context"
    "fmt"
    "strconv"
    "log"
    "os"
    "time"
    "encoding/json"

    "google.golang.org/grpc"
    pb "../redis_read"
)

const (
    address     = "localhost:50051"
    defaultKey = "t0001"
)

// ---------------------------------------------------------------
func main() {
    // Set up a connection to the server.
    conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    c := pb.NewGreeterClient(conn)

    // Contact the server and print out its response.
    key := defaultKey
    if len(os.Args) > 1 {
        key = os.Args[1]
    }
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    r, err := c.RedisRead(ctx, &pb.RedisRequest{Key: key})
    if err != nil {
        log.Fatalf("could not greet: %v", err)
    }
    str_json := r.GetStrjson()
//  log.Printf("Greeting: %s", str_json)

    var unit_aa map[string]interface{}

    json.Unmarshal ([]byte(str_json), &unit_aa)

    fmt.Printf ("%s\t",key)
    population := int(unit_aa["population"].(float64)) 
    str_population := strconv.Itoa(population)
    fmt.Printf ("%s\t",str_population)
    fmt.Printf ("%s\t",unit_aa["name"])
    fmt.Println (unit_aa["date_mod"])
}

// ---------------------------------------------------------------

我将创建gRPC的代码。

脚本

protoc -I redis_read redis_read/redis_read.proto --go_out=plugins=grpc:redis_read

启动服务器程序

go run redis_read_server/main.go

执行客户端程序

$ go run redis_read_client/main.go t1855
t1855   17859   勝山  1921-6-24
广告
将在 10 秒后关闭
bannerAds