简体   繁体   English

自动释放Redis连接

[英]Automatically disposing Redis connections

Something I've noticed with ServiceStack Redis (admittedly far too late) is that it doesn't automatically dispose of it's connections when it's finished with them. 我注意到ServiceStack Redis的一件事(很晚为时已晚)是,在完成连接后,它不会自动释放其连接。 If you forget to dispose them using a using statement or call dispose(), it's left for Redis itself to time them out and get rid of them, but this can take a long time and can end up with ridiculous numbers of idle connections. 如果您忘记使用using语句或调用dispose()来处理它们,则Redis本身会自行使它们超时并摆脱它们,但这可能会花费很长时间,并且最终会导致大量的空闲连接。

So what I'm wondering is if there's some way to tell the garbage collection to automatically dispose of the connections just in case. 所以我想知道的是,是否有某种方法可以告诉垃圾回收自动处理连接,以防万一。

The Redis Clients encapsulates a TCP Connection which does need to be explicitly disposed after you've finished using it. Redis客户端封装了一个TCP连接,在您使用完它之后确实需要对其进行显式处理。 If you're using a Pooled Redis ClientManager this just returns the client back into the Pool (ie it doesn't close the TCP connection). 如果您使用池化Redis ClientManager,这只会将客户端返回池中(即,它不会关闭TCP连接)。

If you access the base.Redis property in your ServiceStack Service it's only created when it's used and does get disposed automatically by using a lazy property and disposing it in the Services Dispose() method, eg: 如果访问ServiceStack Service中的base.Redis属性,则仅在使用它时创建它,并且确实会通过使用惰性属性并在Services Dispose()方法中对其进行处置来自动进行处置,例如:

public class Service 
{
    private IRedisClient redis;
    public virtual IRedisClient Redis
    {
        get { return redis ?? (redis = RedisManager.GetClient()); }
    }

    public virtual void Dispose()
    {
        if (redis != null)
            redis.Dispose();
    }
}

You can follow a similar pattern in your dependencies, otherwise you should use a using statement to ensure the client is always disposed after use, eg: 您可以在依赖项中遵循类似的模式,否则应使用using语句以确保在使用后始终将客户端丢弃,例如:

using (var redis = redisManager.GetClient())
{
    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM