Go の gRPC で Redis のデータを読む (Read)

設定ファイル、サーバープログラム、クライアントプログラムの３つが必要です。

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

設定ファイル

```text:redis_read/redis_read.proto

syntax = "proto3";

package redis_read;

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

message RedisRequest {
	string key = 1;
}

message RedisReply {
	string strjson = 1;
}
```

サーバープログラム

```go:redis_read_server/main.go
// ---------------------------------------------------------------
//
//	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)
	}
}

// ---------------------------------------------------------------
```

クライアントプログラム

```go:redis_read_client/main.go
// ---------------------------------------------------------------
//
//	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 のコードを作成します。

スクリプト

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

サーバープログラムの起動

```bash
go run redis_read_server/main.go
```

クライアントプログラムの実行

```text
$ go run redis_read_client/main.go t1855
t1855	17859	勝山	1921-6-24
```