Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ZevFung opened this issue Apr 8, 2023 · 2 comments
Open

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

ZevFung opened this issue Apr 8, 2023 · 2 comments

Comments

@ZevFung
Copy link

ZevFung commented Apr 8, 2023

是否可以在设置缓存和获取缓存时,动态修改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"

@2881099
Copy link
Owner

2881099 commented Apr 12, 2023

不支持,也没有尝试过。

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

@ZevFung
Copy link
Author

ZevFung commented May 23, 2023

谢谢提供思路,我看了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;
                    }
                }
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants