我正在设计一个使用Redis作为数据库的Web服务,我想知道使用Redis连接StackService客户端的最佳实践.
关键是我一直在阅读Redis,我发现与服务器交互的最佳方式是使用单个并发连接.
问题是,尽管每次Web客户端向Web服务发出请求时我都在使用PooledRedisClientManager,但我得到了一个连接到redis服务器的连接客户端(打开的连接),并且这个连接的客户端数量增加了更多的记忆.
样本'故障'代码:
PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
redisClient.Set("key1", "value1");
}
Run Code Online (Sandbox Code Playgroud)
我为解决这个问题所做的是创建一个用静态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 …
Run Code Online (Sandbox Code Playgroud)