使用Sentinel作为GRPC限流组件,以及使用redis持久化限流规则

一.使用sentinel作为GRPC的限流组件

sentinel官方https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E6%B5%81%E6%A1%86%E6%9E%B6%E7%9A%84%E9%80%82%E9%85%8D#grpc

在官方文档中告诉我们只需要

Server server = ServerBuilder.forPort(port)
     .addService(new MyServiceImpl()) // 添加自己的服务实现
     .intercept(new SentinelGrpcServerInterceptor()) // 在此处注册拦截器
     .build();

这样就可以使用sentinel作为GRPC的限流组件,但是老项目并没有用到或者我们的部分项目不需要sentinel,这样的话,我们需要自适应判断添加SentinelGrpcServerInterceptor。

我重写了阿里的SentinelGrpcServerInterceptor,毕竟Flow control limit exceeded (server side)这句话不是很适合。

class XXXXSentinelGrpcServerInterceptor(fallbackMessage: String) : SentinelGrpcServerInterceptor() {

    private val status = Status.UNAVAILABLE.withDescription(
            fallbackMessage)

    private val STATUS_RUNTIME_EXCEPTION = StatusRuntimeException(Status.CANCELLED)

    override fun <ReqT, RespT> interceptCall(call: ServerCall<ReqT, RespT>, headers: Metadata?, next: ServerCallHandler<ReqT, RespT>): ServerCall.Listener<ReqT>? {
        val fullMethodName = call.methodDescriptor.fullMethodName
        // Remote address: serverCall.getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
        var entry: Entry? = null
        return try {
            entry = SphU.asyncEntry(fullMethodName, EntryType.IN)
            val atomicReferenceEntry = AtomicReference<Entry?>(entry)
            // Allow access, forward the call.
            object : ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
                    next.startCall(
                            object : ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
                                override fun close(status: Status, trailers: Metadata) {
                                    val entry = atomicReferenceEntry.get()
                                    if (entry != null) {
                     
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值