Grpc之metadata

简介: qcy-blog

hello.proto
syntax="proto3";
package pb;
option go_package = "./pb";
service Greeter {
rpc SayHello(HelloRequest) returns(HelloReply){}
}

message HelloRequest {
string name = 1;
}

[kod.nmghsjz.com)
[kod.nc90.com)
[kod.respectator.com)
[kod.njhxpx.com)
[kod.npjr.net)
[kod.oilfriends.com)
message HelloReply {
string message = 1;
}
protoc -I . --go_out=. --go-grpc_out=. ./hello.proto
server
package main

import (
"context"
"flag"
"fmt"
"demo/protos"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"log"
"net"
)

var host = "127.0.0.1"

var (
ServiceName = flag.String("ServiceName", "hello_service", "service name")
Port = flag.Int("Port", 50001, "listening port")
)

type server struct {
}

func main() {
flag.Parse()

lis, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", *Port))
if err != nil {
    log.Fatalf("failed to listen:%s", err)
} else {
    fmt.Printf("listen at :%d\n", *Port)
}

defer lis.Close()

s := grpc.NewServer()
defer s.GracefulStop()

protos.RegisterGreeterServer(s, &server{})
addr := fmt.Sprintf("%s:%d", host, *Port)
fmt.Printf("server add:%s\n", addr)

if err := s.Serve(lis); err != nil {
    fmt.Printf("failed to server: %s", err)
}

}

func (s server) SayHello(ctx context.Context, in protos.HelloRequest) (*protos.HelloReply, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
fmt.Printf("get metadata error")
}else{
fmt.Println("get metadata success: ",md)
}
if t, ok := md["timestamp"]; ok {
fmt.Printf("timestamp from metadata:\n")
for i, e := range t {
fmt.Printf(" %d. %s\n", i, e)
}
}
if t1, ok1 := md["key1"]; ok1 {
fmt.Printf("key1 from metadata:\n")
for i, e := range t1 {
fmt.Printf(" %d . %s\n", i, e)
}
}
if len(md) > 0 {
for k, v := range md {
fmt.Printf("%v:%v\n", k, v)
}
}
return &protos.HelloReply{Message: "server: " + in.Name}, nil
}
client
package main

import (
"context"
"fmt"
"demo/protos"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"time"
)

const (
timestampFormat = time.StampNano
)

func main() {
conn, err := grpc.Dial("127.0.0.1:50001", grpc.WithInsecure())
if err != nil {
panic(err)
}

client := protos.NewGreeterClient(conn)
md := metadata.Pairs("timestamp", time.Now().Format(timestampFormat))
md = metadata.New(map[string]string{"key1": "val1", "key2": "val2"})
ctx := metadata.NewOutgoingContext(context.Background(), md)
resp, err := client.SayHello(ctx, &protos.HelloRequest{Name: "Hello"})
if err == nil {
    fmt.Printf("Reply is : %s\n", resp.Message)
} else {
    fmt.Printf("call server error:%s\n", err)
}

}

运行
go run server.go
listen at :50001
server add:127.0.0.1:50001
get metadata success: map[:authority:[127.0.0.1:50001] content-type:[application/grpc] key1:[val1] key2:[val2] user-agent:[grpc-go/1.53.0]]
key1 from metadata:
0 . val1
:authority:[127.0.0.1:50001]
content-type:[application/grpc]
user-agent:[grpc-go/1.53.0]
key2:[val2]
key1:[val1]

#

go run client.go
Reply is : server: Hello

相关文章
|
Kubernetes 应用服务中间件 API
5 分钟了解 Kubernetes Ingress 和 Gateway API
5 分钟了解 Kubernetes Ingress 和 Gateway API
663 0
|
JSON Kubernetes API
Kubernetes ImagePolicyWebhook与ValidatingAdmissionWebhook【3】validating_admission.go源码解析
Kubernetes ImagePolicyWebhook与ValidatingAdmissionWebhook【3】validating_admission.go源码解析
Kubernetes ImagePolicyWebhook与ValidatingAdmissionWebhook【3】validating_admission.go源码解析
|
Kubernetes 容器
Kubernetes CKS 2021【4】---Cluster Setup - Secure Ingress
Kubernetes CKS 2021【4】---Cluster Setup - Secure Ingress
Kubernetes CKS 2021【4】---Cluster Setup - Secure Ingress
|
XML JSON NoSQL
gRPC-shop:什么是 gRPC(一)
gRPC-shop:什么是 gRPC(一)
162 0
gRPC-shop:什么是 gRPC(一)
|
Kubernetes Cloud Native 应用服务中间件
kubernetes Deployment【4】 client-go 管理 deployment
kubernetes Deployment【4】 client-go 管理 deployment
|
Kubernetes API 容器
kubernetes sample-apiserver解析
kubernetes sample-apiserver解析
|
Kubernetes 容器
Kubernetes 的Ingress的Rewrite annotations
Kubernetes 的Ingress的Rewrite annotations
281 0
Kubernetes 的Ingress的Rewrite annotations
|
运维 Kubernetes Cloud Native
上了 istio 的贼船之 API Gateway
通过将传统微服务架构的这些控制面功能解耦到 istio,可以让微服务应用本身专注于业务开发,是一个比较简的单体 springboot 应用。再结合 k8s 的高扩展性,研发整体的迭代速度和运维效率还是比较高的,缺点是无论是 k8s 还是 istio ,学习成本偏高,需要团队至少 2 人具有专业知识,对于招聘成本、系统升级都有风险。
上了 istio 的贼船之 API Gateway
|
应用服务中间件 Shell nginx
Istio - TrafficManagement - Timeout
超时是为了解决长时间或者无限期的等待造成服务不可用,通常需要在代码中植入此类的网络层面的弹性处理逻辑,但通过 Istio 就可以使用 Vitual Sevice来优雅的实现超时的处理。
162 0
Istio - TrafficManagement - Timeout
|
Kubernetes 负载均衡 搜索推荐
Istio - crds - Vistrual Service
虚拟服务(Vistrual Service)是 Istio 重要的资源对象之一,作用是将流量路由到网格中的服务。支持基于权重、http header条件等优先级的路由,比Kuberentes service对于流量的管控更加的丰富,颗粒度更加精细。
216 0
Istio - crds - Vistrual Service