interceptor

package
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2022 License: MIT Imports: 20 Imported by: 13

README

interceptor

常用grpc客户端和服务端的拦截器。


使用示例

jwt
// grpc server

func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// token鉴权
	options = append(options, grpc.UnaryInterceptor(
	    interceptor.UnaryServerJwtAuth(
	        // middleware.WithAuthClaimsName("tokenInfo"), // 设置附加到ctx的鉴权信息名称,默认是tokenInfo
	        middleware.WithAuthIgnoreMethods( // 添加忽略token验证的方法
	            "/proto.Account/Register",
	        ),
	    ),
	))

	return options
}

// 生成鉴权信息authorization
func (a *Account) Register(ctx context.Context, req *serverNameV1.RegisterRequest) (*serverNameV1.RegisterReply, error) {
    // ......
	token, err := jwt.GenerateToken(uid)
	// handle err
	authorization = middleware.GetAuthorization(token) // 加上前缀
    // ......
}

// 客户端调用方法时必须把鉴权信息通过context传递进来,key名称必须是authorization
func getUser(client serverNameV1.AccountClient, req *serverNameV1.RegisterReply) error {
	md := metadata.Pairs("authorization", req.Authorization)
	ctx := metadata.NewOutgoingContext(context.Background(), md)

	resp, err := client.GetUser(ctx, &serverNameV1.GetUserRequest{Id: req.Id})
	if err != nil {
		return err
	}

	fmt.Println("get user success", resp)
	return nil
}

logging
var logger *zap.Logger

func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// 日志设置,默认打印客户端断开连接信息,示例 https://pkg.go.dev/github.com/grpc-ecosystem/go-grpc-middleware/logging/zap
	options = append(options, grpc_middleware.WithUnaryServerChain(
		interceptor.UnaryServerCtxTags(),
		interceptor.UnaryServerZapLogging(
			logger.Get(), // zap
			// middleware.WithLogFields(map[string]interface{}{"serverName": "userExample"}), // 附加打印字段
			middleware.WithLogIgnoreMethods("/proto.userExampleService/GetByID"), // 忽略指定方法打印,可以指定多个
		),
	))

	return options
}

recovery
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	recoveryOption := grpc_middleware.WithUnaryServerChain(
		interceptor.UnaryServerRecovery(),
	)
	options = append(options, recoveryOption)

	return options
}

retry
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁用tls
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// 重试
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryClientRetry(
                //middleware.WithRetryTimes(5), // 修改默认重试次数,默认3次
                //middleware.WithRetryInterval(100*time.Millisecond), // 修改默认重试时间间隔,默认50毫秒
                //middleware.WithRetryErrCodes(), // 添加触发重试错误码,默认codes.Internal, codes.DeadlineExceeded, codes.Unavailable
			),
		),
	)
	options = append(options, option)

	return options
}

限流
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁用tls
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// circuit breaker
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryRateLimit(),
		),
	)
	options = append(options, option)

	return options
}

熔断器
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁用tls
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// circuit breaker
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			interceptor.UnaryClientCircuitBreaker(),
		),
	)
	options = append(options, option)

	return options
}

timeout
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁止tls加密
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// 超时拦截器
	option := grpc.WithUnaryInterceptor(
		grpc_middleware.ChainUnaryClient(
			middleware.ContextTimeout(time.Second), // //设置超时
		),
	)
	options = append(options, option)

	return options
}

tracing
// 初始化trace
func InitTrace(serviceName string) {
	exporter, err := tracer.NewJaegerAgentExporter("192.168.3.37", "6831")
	if err != nil {
		panic(err)
	}

	resource := tracer.NewResource(
		tracer.WithServiceName(serviceName),
		tracer.WithEnvironment("dev"),
		tracer.WithServiceVersion("demo"),
	)

	tracer.Init(exporter, resource) // 默认采集全部
}

// 在客户端设置链路跟踪
func getDialOptions() []grpc.DialOption {
	var options []grpc.DialOption

	// 禁用tls加密
	options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

	// tracing跟踪
	options = append(options, grpc.WithUnaryInterceptor(
		interceptor.UnaryClientTracing(),
	))

	return options
}

// 在服务端设置链路跟踪
func getServerOptions() []grpc.ServerOption {
	var options []grpc.ServerOption

	// 链路跟踪拦截器
	options = append(options, grpc.UnaryInterceptor(
		interceptor.UnaryServerTracing(),
	))

	return options
}

// 如果有需要,可以在程序创建一个span
func SpanDemo(serviceName string, spanName string, ctx context.Context) {
	_, span := otel.Tracer(serviceName).Start(
		ctx, spanName,
		trace.WithAttributes(attribute.String(spanName, time.Now().String())), // 自定义属性
	)
	defer span.End()

	// ......
}

metrics

使用示例 metrics


Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrLimitExceed = rl.ErrLimitExceed

ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.

ErrNotAllowed error not allowed.

Functions

func GetAuthCtxKey

func GetAuthCtxKey() string

GetAuthCtxKey 获取Claims的名称

func GetAuthorization

func GetAuthorization(token string) string

GetAuthorization 根据token组合成鉴权信息

func JwtVerify

func JwtVerify(ctx context.Context) (context.Context, error)

JwtVerify 从context获取authorization来验证是否合法,authorization组成格式:authScheme token

func SteamClientCircuitBreaker added in v1.4.0

func SteamClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamClientInterceptor

SteamClientCircuitBreaker client-side stream circuit breaker interceptor

func SteamServerCircuitBreaker added in v1.4.0

func SteamServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamServerInterceptor

SteamServerCircuitBreaker server-side stream circuit breaker interceptor

func StreamClientLog added in v1.4.0

func StreamClientLog(logger *zap.Logger, opts ...grpc_zap.Option) grpc.StreamClientInterceptor

StreamClientLog 客户端日志stream拦截器

func StreamClientMetrics

func StreamClientMetrics() grpc.StreamClientInterceptor

StreamClientMetrics 客户端指标stream拦截器

func StreamClientRetry

func StreamClientRetry(opts ...RetryOption) grpc.StreamClientInterceptor

StreamClientRetry 重试stream拦截器

func StreamClientTracing

func StreamClientTracing() grpc.StreamClientInterceptor

StreamClientTracing 客户端链路跟踪stream拦截器

func StreamServerCtxTags

func StreamServerCtxTags() grpc.StreamServerInterceptor

StreamServerCtxTags extractor field stream拦截器

func StreamServerJwtAuth

func StreamServerJwtAuth(opts ...AuthOption) grpc.StreamServerInterceptor

StreamServerJwtAuth jwt鉴权stream拦截器

func StreamServerLog

func StreamServerLog(logger *zap.Logger, opts ...LogOption) grpc.StreamServerInterceptor

StreamServerLog 服务端日志stream拦截器

func StreamServerMetrics

func StreamServerMetrics(opts ...metrics.Option) grpc.StreamServerInterceptor

StreamServerMetrics 服务端指标stream拦截器

func StreamServerRateLimit

func StreamServerRateLimit(opts ...RatelimitOption) grpc.StreamServerInterceptor

StreamServerRateLimit server-side stream circuit breaker interceptor

func StreamServerRecovery

func StreamServerRecovery() grpc.StreamServerInterceptor

StreamServerRecovery recovery stream拦截器

func StreamServerTracing

func StreamServerTracing() grpc.StreamServerInterceptor

StreamServerTracing 服务端链路跟踪stream拦截器

func StreamTimeout

func StreamTimeout(d time.Duration) grpc.StreamClientInterceptor

StreamTimeout 超时stream拦截器

func UnaryClientCircuitBreaker added in v1.4.0

func UnaryClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryClientInterceptor

UnaryClientCircuitBreaker client-side unary circuit breaker interceptor

func UnaryClientLog

func UnaryClientLog(logger *zap.Logger, opts ...grpc_zap.Option) grpc.UnaryClientInterceptor

UnaryClientLog 客户端日志unary拦截器

func UnaryClientMetrics

func UnaryClientMetrics() grpc.UnaryClientInterceptor

UnaryClientMetrics 客户端指标unary拦截器

func UnaryClientRetry

func UnaryClientRetry(opts ...RetryOption) grpc.UnaryClientInterceptor

UnaryClientRetry 重试unary拦截器

func UnaryClientTracing

func UnaryClientTracing() grpc.UnaryClientInterceptor

UnaryClientTracing 客户端链路跟踪unary拦截器

func UnaryServerCircuitBreaker added in v1.4.0

func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInterceptor

UnaryServerCircuitBreaker server-side unary circuit breaker interceptor

func UnaryServerCtxTags

func UnaryServerCtxTags() grpc.UnaryServerInterceptor

UnaryServerCtxTags extractor field unary拦截器

func UnaryServerJwtAuth

func UnaryServerJwtAuth(opts ...AuthOption) grpc.UnaryServerInterceptor

UnaryServerJwtAuth jwt鉴权unary拦截器

func UnaryServerLog

func UnaryServerLog(logger *zap.Logger, opts ...LogOption) grpc.UnaryServerInterceptor

UnaryServerLog 服务端日志unary拦截器

func UnaryServerMetrics

func UnaryServerMetrics(opts ...metrics.Option) grpc.UnaryServerInterceptor

UnaryServerMetrics 服务端指标unary拦截器

func UnaryServerRateLimit

func UnaryServerRateLimit(opts ...RatelimitOption) grpc.UnaryServerInterceptor

UnaryServerRateLimit server-side unary circuit breaker interceptor

func UnaryServerRecovery

func UnaryServerRecovery() grpc.UnaryServerInterceptor

UnaryServerRecovery recovery unary拦截器

func UnaryServerTracing

func UnaryServerTracing() grpc.UnaryServerInterceptor

UnaryServerTracing 服务端链路跟踪unary拦截器

func UnaryTimeout

func UnaryTimeout(d time.Duration) grpc.UnaryClientInterceptor

UnaryTimeout 超时unary拦截器

Types

type AuthOption

type AuthOption func(*AuthOptions)

AuthOption 设置鉴权字段

func WithAuthClaimsName

func WithAuthClaimsName(claimsName string) AuthOption

WithAuthClaimsName 设置鉴权的信息在ctx的key名称

func WithAuthIgnoreMethods

func WithAuthIgnoreMethods(fullMethodNames ...string) AuthOption

WithAuthIgnoreMethods 忽略鉴权的方法 fullMethodName格式: /packageName.serviceName/methodName, 示例/api.userExample.v1.userExampleService/GetByID

func WithAuthScheme

func WithAuthScheme(scheme string) AuthOption

WithAuthScheme 设置鉴权的信息前缀

type AuthOptions

type AuthOptions struct {
	// contains filtered or unexported fields
}

AuthOptions 鉴权设置

type CircuitBreakerOption added in v1.4.0

type CircuitBreakerOption func(*circuitBreakerOptions)

CircuitBreakerOption set the circuit breaker circuitBreakerOptions.

func WithGroup added in v1.4.0

func WithGroup(g *group.Group) CircuitBreakerOption

WithGroup with circuit breaker group. NOTE: implements generics circuitbreaker.CircuitBreaker

type LogOption

type LogOption func(*logOptions)

LogOption 日志设置

func WithLogFields

func WithLogFields(kvs map[string]interface{}) LogOption

WithLogFields 添加自定义打印字段

func WithLogIgnoreMethods

func WithLogIgnoreMethods(fullMethodNames ...string) LogOption

WithLogIgnoreMethods 忽略打印的方法 fullMethodName格式: /packageName.serviceName/methodName, 示例/api.userExample.v1.userExampleService/GetByID

type RatelimitOption added in v1.4.0

type RatelimitOption func(*ratelimitOptions)

RatelimitOption set the rate limits ratelimitOptions.

func WithBucket added in v1.4.0

func WithBucket(b int) RatelimitOption

WithBucket with bucket size.

func WithCPUQuota added in v1.4.0

func WithCPUQuota(quota float64) RatelimitOption

WithCPUQuota with real cpu quota(if it can not collect from process correct);

func WithCPUThreshold added in v1.4.0

func WithCPUThreshold(threshold int64) RatelimitOption

WithCPUThreshold with cpu threshold

func WithWindow added in v1.4.0

func WithWindow(d time.Duration) RatelimitOption

WithWindow with window size.

type RetryOption

type RetryOption func(*retryOptions)

RetryOption set the retry retryOptions.

func WithRetryErrCodes

func WithRetryErrCodes(errCodes ...codes.Code) RetryOption

WithRetryErrCodes 设置触发重试错误码

func WithRetryInterval

func WithRetryInterval(t time.Duration) RetryOption

WithRetryInterval 设置重试时间间隔,范围1毫秒到10秒

func WithRetryTimes

func WithRetryTimes(n uint) RetryOption

WithRetryTimes 设置重试次数,最大10次

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL