Redis serviceStack池化连接客户端
我正在设计一个使用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"); }
这是一个好习惯吗?
先感谢您!
我使用了PooledRedisClientManager
,它运行正常:
我只运行一次的示例代码:
static PooledRedisClientManager pooledClientManager = new PooledRedisClientManager("localhost");
和我在许multithreading上运行的代码:
var redisClient = pooledClientManager.GetClient(); using (redisClient) { redisClient.Set("key" + i.ToString(), "value1"); }
我只有11个客户端连接到服务器。
上述就是C#学习教程:Redis serviceStack池化连接客户端分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/958096.html