2881099/FreeRedis

请问如何缓存key支持多租户

ZevFung opened this issue · 2 comments

是否可以在设置缓存和获取缓存时,动态修改key,类似拦截器
当前请求header的tenant-id=1
var r = new RedisClient("127.0.0.1");
r.handlerKey+= (key) =>
{
return tenant-id+":"+key
};
例如, redis.set("list","aaa")
拦截key="list",修改为key="1:list"

不支持,也没有尝试过。

试试 r.Interceptors 处理?参考下源代码

谢谢提供思路,我看了Interceptors相关的,这样写拦截key动态修改。

public class TenantInterceptorTests
    {
        public static RedisClient CreateClient() => new RedisClient(RedisEnvironmentHelper.GetHost("redis_interceptor"));

        [Fact]
        public void Interceptor()
        {
            using (var cli = CreateClient())
            {
                cli.Interceptors.Add(() => new RedisCacheAop());

                cli.Set("Interceptor01_{tenantId}", "123123");
                var val = cli.Get("Interceptor01_{tenantId}");

                Assert.Equal("123123", val);
            }
        }
    }

    class RedisCacheAop : IInterceptor
    {
        public void After(InterceptorAfterEventArgs args)
        {
        }
        
        public void Before(InterceptorBeforeEventArgs args)
        {
            if (args.Command._keyIndexes.Count > 0)
            {
                var key = args.Command.GetKey(0);
                if (!string.IsNullOrWhiteSpace(key))
                {
                    Regex reg = new Regex("\\{tenantId\\}");
                    if (reg.IsMatch(key))
                    {
                        key = Regex.Replace(key, "\\{tenantId\\}", "1");
                        args.Command._input[args.Command._keyIndexes[0]] = key;
                    }
                }
            }
        }
    }
}