【问题标题】:Redis serviceStack pooled connection clientRedis serviceStack 池化连接客户端
【发布时间】: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


【解决方案1】:

我使用了PooledRedisClientManager,效果很好:

示例代码我只运行一次

static PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");

以及我在许多线程上运行的代码:

var redisClient = pooledClientManager.GetClient();
using (redisClient)
{
    redisClient.Set("key" + i.ToString(), "value1");
}

我只有 11 个客户端连接到服务器。

【讨论】:

  • 如果我这样做,我会在浏览器发出的每个请求中获得一个新线程。我已经对其进行了调试,并在 redisClient.Set("key" + i.ToString(), "value1"); 行创建了一个新线程(客户端)。被执行,我失去了控制,似乎它将永远打开。我做了一个测试,刷新了调用服务 URL 的网页,我已经连接了 100 个客户端
  • 也许问题是我对每个请求都运行代码,是吗?
  • 你确定你没有运行"PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");"每次?
  • 是的,我在每个请求中都运行它,是不是错了?正确的用法是什么?
  • 您需要定义一个包含 pooledClientManager 的静态成员。对于每个请求,您都需要引用该静态成员(无需创建它的新实例)并运行“使用(var redisClient = ...”代码。只要确保您没有实例化PooledRedisClientManager 不止一次
猜你喜欢
  • 2021-10-22
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多