Redis性能大幅提升之性能大幅提升之Batch批量读写详解批量读写详解
主要给大家介绍了关于Redis性能大幅提升之Batch批量读写的相关资料,文中介绍的非常详细,对大家具有一
定的参考学习价值,需要的朋友们下面来跟着小编一起来学习学习吧。
前言前言
本文主要介绍的是关于Redis性能提升之Batch批量读写的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:
提示:本文针对的是StackExchange.Redis
一、问题呈现一、问题呈现
前段时间在开发的时候,遇到了redis批量读的问题,由于在StackExchange.Redis里面我确实没有找到PipeLine命令,找到的
是Batch命令,因此对其用法进行了探究一下。
下面的代码是我之前写的:下面的代码是我之前写的:
public List<StudentEntity> Get(List<int> ids)
{
List<StudentEntity> result = new List<StudentEntity>();
try
{
var db = RedisCluster.conn.GetDatabase();
foreach (int id in ids.Keys)
{
string key = KeyManager.GetKey(id);
var dic = db.HashGetAll(key).ToDictionary(k => k.Name, v => v.Value);
StudentEntity se = new StudentEntity();
if (dic.Keys.Contains(StudentEntityRedisHashKey.id.ToString()))
{
pe.id = FormatUtils.ConvertToInt32(dic[StudentEntityRedisHashKey.id.ToString()], -1);
}
if (dic.Keys.Contains(StudentEntityRedisHashKey.name.ToString()))
{
pe.name= dic[StudentEntityRedisHashKey.name.ToString()];
}
result.Add(se);
}
catch (Exception ex)
{
}
return result;
}
从上面的代码中可以看出,并不是批量读,经过性能测试,性能确实是要远远低于用Batch操作,因为HashGetAll方法被执行
了多次。
下面给出批量方法:
二、解决问题方法二、解决问题方法
具体的用法是:
var batch = db.CreateBatch();
...//这里写具体批量操作的方法
batch.Execute();
2.1批量写:批量写:
具体代码:
public bool InsertBatch(List<StudentEntity> seList)
{
bool result = false;
try
{
var db = RedisCluster.conn.GetDatabase();
var batch = db.CreateBatch();
foreach (var se in seList)
{
string key = KeyManager.GetKey(se.id);
batch.HashSetAsync(key, StudentEntityRedisHashKey.id.ToString(), te.id);
batch.HashSetAsync(key, StudentEntityRedisHashKey.name.ToString(), te.name);