栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

grpc拦截器的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

grpc拦截器的使用

gRPC作为通用RPC框架,内置了拦截器功能。包括服务器端的拦截器和客户端拦截器,使用上大同小异。主要作用是在rpc调用的前后进行额外处理。

拦截器在很多场景中使用,比如调用接口前验证用户是否登录,比如接口中判断用户的useragent做一些反爬的策略等等,大量的情况就是把请求拦截一下,做一下接口的预处理,我们不可能在每个接口中都写一遍,需要做统一的拦截器。

实现简单的拦截器 1)服务端:grpc.UnaryInterceptor(interceptor)

interceptor是自定义的拦截器函数,追踪函数的参数可知,interceptor是一个:

type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)

参数含义: 

ctx context.Context:请求上下文req interface{}:RPC 方法的请求参数info *UnaryServerInfo:RPC 方法的所有信息handler UnaryHandler:RPC 方法真正执行的逻辑

 案例:

//拦截器
interceptor :=  func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error){
	fmt.Println("接收到了一个新的请求")
	res,err := handler(ctx, req)
	fmt.Println("请求已完成")
	return res, err
}
opt := grpc.UnaryInterceptor(interceptor)
g := grpc.NewServer(opt)
//...
2)客户端:grpc.WithUnaryInterceptor(interceptor)

interceptor是自定义的拦截器函数,追踪函数的参数可知,interceptor是一个:

type UnaryClientInterceptor func(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error

案例:

interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error{
	start := time.Now()
	err := invoker(ctx, method, req, reply, cc, opts...)
	fmt.Printf("耗时:%sn", time.Since(start))
	return err
}
opt := grpc.WithUnaryInterceptor(interceptor)
conn, err := grpc.Dial(":8083", grpc.WithInsecure(), opt)
//...
3)一些开源的拦截器

https://github.com/grpc-ecosystem/go-grpc-middleware

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/735546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号