feat(client): add cache client

This commit is contained in:
bandl 2021-10-17 17:20:01 +08:00
parent aade8e8edb
commit 5fe201ca32
3 changed files with 71 additions and 0 deletions

22
client/client.go Normal file
View File

@ -0,0 +1,22 @@
package client
import (
"gitee.com/timedb/wheatCache/client/middle"
"gitee.com/timedb/wheatCache/pkg/proto"
"google.golang.org/grpc"
)
func newWheatClient(targer string, opt ...middle.ClientMiddle) (proto.CommServerClient, error) {
interceptor := middle.GetUnaryInterceptor(opt...)
comm, err := grpc.Dial(targer, grpc.WithInsecure(), grpc.WithUnaryInterceptor(interceptor))
if err != nil {
return nil, err
}
return proto.NewCommServerClient(comm), nil
}
func NewWheatClient(targer string, opt ...middle.ClientMiddle) (proto.CommServerClient, error) {
return newWheatClient(targer, opt...)
}

6
client/middle/define.go Normal file
View File

@ -0,0 +1,6 @@
package middle
import "context"
// type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error
type ClientMiddle func(ctx context.Context, method string, req, reply interface{}, header map[string]string) error

43
client/middle/middle.go Normal file
View File

@ -0,0 +1,43 @@
package middle
import (
"context"
"gitee.com/timedb/wheatCache/pkg/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func WithUnaryColonyClient(ctx context.Context, method string, req, reply interface{}, header map[string]string) error {
key, ok := req.(proto.GetKeyBaseInterface)
if !ok {
return status.Errorf(codes.Unknown, "key base err")
}
if header == nil {
return nil
}
header[proto.BaseKeyMethodKey] = key.GetKey().Key
return nil
}
func GetUnaryInterceptor(middleOpts ...ClientMiddle) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply interface{},
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
// 加载中间件
header := make(map[string]string)
for _, mid := range middleOpts {
err := mid(ctx, method, req, reply, header)
if err != nil {
return err
}
}
for key, value := range header {
ctx = metadata.AppendToOutgoingContext(ctx, key, value)
}
return invoker(ctx, method, req, reply, cc, opts...)
}
}