如何更改redis客户端来自redis池的redis DB
本文关键字:redis 池的 DB 客户端 何更改 | 更新日期: 2023-09-27 18:22:46
当我使用redis池时,我如何更改db(redis命令选择)。
我想要从不同的数据库中写入主机和读取主机。
例如:
刚才我只有一个redis服务器,所以readWriteHosts=readOnlyHosts
pool = RedisDao.CreateManager(hostIp, hostIp);
public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
{
return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
{
MaxWritePoolSize = 50,//
MaxReadPoolSize = 5,//
AutoStart = true,
});
}
public RedisDB ReadRedisForModel(String ID)
{
//这里我想使用数据库编号是第%15
using (var redis = pool.GetClient())
{
RedisDB model = new RedisDB();
Dictionary<string, string> dic = redis.GetAllEntriesFromHash(keyPrefix + ID);
model.ID = ID;//Int32.Parse(ids[i]);
return model;
}
}
public void WriteRedis(RedisDB model)
{
//这里我想使用数据库编号是(第1天)%15
using (var redis = pool.GetClient())
{
编辑:
我找到了一种设置不同数据库的方法,但我觉得这个解决方案不是最好的方法。
if(redis is RedisClient)
{
long db = redis.DB;//db always = 0;
((RedisClient)redis).ChangeDB((day-1)%15);
}
需要锁线程吗?当我读或写信给redis时。恐怕,我在多线程中得到了相同的redis客户端。那么redis DB是?
编辑结束
int time = DateTimeUtil.ConvertDateTimeInt(DateTime.Now);
model.ID = time + redis.Increment(incrementKey, 1) + "";//.Incr("ID");
using (var pip = redis.CreatePipeline())
{
pip.QueueCommand(r => r.AddItemToList(primaryKey, model.ID + ""));
pip.Flush();
};
};
}
我从池中得到了redisClient,但redisClient没有changeDB的功能。
有人知道怎么设置吗?
例如:
//write
bool IsNeedChangeDB=true;
int WriteDBNumber=3
public static PooledRedisClientManager pool = RedisDao.CreateManager(hostIp, hostIp);
using (var redis = pool.GetClient())
{
if (redis is RedisClient && IsNeedChangeDB)
{
if (redis.Db != this.WriteDBNumber)
{
((RedisClient)redis).ChangeDb(this.WriteDBNumber);
}
else
{
Trace.WriteLine("it is a test" + redis.Host);
}
}
redis.Set<string>("key","value");
}
int ReadDBNumber=3;
//read
protected IRedisClient GetRedisClient()
{
var redis = pool.GetClient();
if (redis is RedisClient && IsNeedChangeDB)
{
if (redis.Db != this.ReadDBNumber)
((RedisClient)redis).ChangeDb(this.ReadDBNumber);
}
return redis;
}