【发布时间】:2012-05-22 18:10:45
【问题描述】:
我正在设计一个使用 Redis 作为数据库的 Web 服务,我想知道使用 Redis 连接 StackService 客户端的最佳实践。
关键是我一直在阅读 Redis,发现与服务器交互的最佳方式是使用单个并发连接。
问题是,尽管每次 Web 客户端向 Web 服务发出请求时我都在使用 PooledRedisClientManager,但我得到了一个连接到 redis 服务器的客户端(打开的连接),而这连接的客户端数量增加,但不限制消耗越来越多的内存。
示例“故障”代码:
PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
redisClient.Set("key1", "value1");
}
我为解决这个问题所做的,是创建一个使用静态 RedisClient var; 实现单例模式的类;如果redisClient 未初始化,则创建一个新的,如果是,则返回已初始化的。
解决方案:
public class CustomRedisPooledClient
{
private static CustomRedisPooledClient _instance = null;
public RedisClient redisClient = null;
// Objeto sincronización para hacer el Lock
private static object syncLock = new object();
private CustomRedisPooledClient()
{
redisClient = new RedisClient("localhost");
}
public static CustomRedisPooledClient GetPooledClient()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new CustomRedisPooledClient();
}
}
}
return _instance;
}
}
CustomRedisPooledClient customRedisPooledClient = CustomRedisPooledClient.GetPooledClient();
using (customRedisPooledClient.redisClient)
{
customRedisPooledClient.redisClient.Set("key1", "value1");
}
这是一个好习惯吗?
提前谢谢你!
【问题讨论】:
-
为什么你从池中拉出一个 redisClient 但没有使用它?而是使用 pooledClientManager 代替?
-
问题写错了,现在改正
-
k,虽然我会编辑您的问题,因为您的“故障代码”现在可以工作,并且提供的 解决方案 并不理想。添加问题所在并参考理想解决方案的公认答案。
标签: c# redis servicestack