我的Redis服务器在数据键[urn:Customer]
中有1000个Customer行。
我需要从我的自动完成过程的记录集中获取分页结果。
我的代码:
var custDetails = from C in nwDB.Customers
select new {
C.CustomerID, C.CompanyName,
C.ContactName, C.City,
C.Country, C.PostalCode,
C.Phone, C.Fax
};
using (var redis = new RedisClient())
{
redis.FlushDb();
redis.FlushAll();
var RedisUsers = redis.As<CustomerR>();
RedisUsers.SetSequence(0);
foreach (var eachCustomer in custDetails)
{
RedisUsers.Store(new CustomerR
{
RedisCustID = RedisUsers.GetNextSequence(),
CustomerID = eachCustomer.CustomerID,
CompanyName = eachCustomer.CompanyName,
ContactName = eachCustomer.ContactName,
City = eachCustomer.City,
Country = eachCustomer.PostalCode,
Phone = eachCustomer.Phone,
Fax = eachCustomer.Fax
});
}
var allThepeople = RedisUsers.GetAll();
gvCustomers.DataSource = allThepeople;
gvCustomers.DataBind();
}
我需要使用GetAll()
值仅显示前50行,而不是RedisUsers.GetNextSequence()
。
答案 0 :(得分:3)
最好将每个客户存储为自己的密钥。 即。 urn:Customer:123
代表CustomerID
= 123。
这使我们能够通过选择该密钥来通过其ID访问客户。但它也允许我们SCAN
匹配Customer键模式的键。即urn:Customer:<id>
。
您还可以避免创建任意RedisCustID
,只需使用CustomerID
,就可以避免很多混乱。
var custDetails = from c in nwDB.Customers select new {
c.CustomerID,
c.CompanyName,
c.ContactName,
c.City,
c.Country,
c.PostalCode,
c.Phone,
c.Fax
};
using (var redis = new RedisClient())
{
var customers = redis.As<CustomerR>();
foreach(var customer in custDetails)
{
// The key for this customer
var customerKey = string.Format("Customer:{0}", customer.CustomerID);
// Store the customer
// Use ConvertTo<T> to auto map the properties
customers.SetEntry(customerKey, customer.ConvertTo<CustomerR>());
}
}
using (var redis = new RedisClient())
{
var customers = redisClient.As<CustomerR>();
var customerKey = string.Format("Customer:{0}", 123);
var customer = customers.GetValue(customerKey);
}
using (var redis = new RedisClient())
{
var customerKeys = redis.ScanAllKeys("Customer:*").ToList();
var allCustomers = redis.GetValues<CustomerR>(customerKeys);
}
ScanAllKeys
方法允许您分页结果,这最终是您要做的。
using (var redis = new RedisClient())
{
var customerKeys = redis.ScanAllKeys("Customer:*", 50).ToList();
var top50Customers = redis.GetValues<CustomerR>(customerKeys);
}
即。获得第10页的第3页
int page = 3;
int pageSize = 10;
int startAt = pageSize * page;
int endAt = startAt + pageSize;
using (var redis = new RedisClient())
{
var pagedCustomerKeys = redis.ScanAllKeys("Customer:*", endAt).ToList().Skip(startAt).Take(pageSize);
var pagedCustomers = redis.GetValues<CustomerR>(pagedCustomerKeys);
}
如果您想了解如何更新客户或删除客户see this answer,请提供更多示例。
我希望有所帮助。