我正在设计一个使用 Redis 作为数据库的 Web 服务,我想了解使用 Redis 与 StackService 客户端连接的最佳实践。
重点是,我一直在阅读有关 Redis 的内容,并且发现与服务器交互的最佳方式是使用单个并发连接。
问题是尽管我正在使用池化RedisClientManager每次 Web 客户端向 Web 服务发出请求时,我都会获得一个与 Redis 服务器的更多连接客户端(打开的连接),并且连接客户端的数量会不断增加,并且不会消耗越来越多的内存。
示例“错误”代码:
PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
redisClient.Set("key1", "value1");
}
我为解决这个问题所做的就是创建一个类,使用静态实现单例模式RedisClient
变量;其中如果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");
}
这是一个好的做法吗?
先感谢您!
I used PooledRedisClientManager
它工作正常:
示例代码我只跑一次:
static PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
和我在许多线程上运行的代码:
var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
redisClient.Set("key" + i.ToString(), "value1");
}
我只有 11 个客户端连接到服务器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)