Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Redis缓存中存储列表元素_C#_Azure_Redis_Stackexchange.redis_<img Src="//i.stack.imgur.com/WM7S8.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">servicestack.redis - Fatal编程技术网 servicestack.redis,C#,Azure,Redis,Stackexchange.redis,servicestack.redis" /> servicestack.redis,C#,Azure,Redis,Stackexchange.redis,servicestack.redis" />

C# 如何在Redis缓存中存储列表元素

C# 如何在Redis缓存中存储列表元素,c#,azure,redis,stackexchange.redis,servicestack.redis,C#,Azure,Redis,Stackexchange.redis,servicestack.redis,我在c#Redis缓存中使用了StackExchange.Redis cache.StringSet("Key1", CustomerObject); 但我想像这样存储数据 cache.StringSet("Key1", ListOfCustomer); 因此,一个键存储了所有客户列表,并且很容易 搜索、分组、筛选该列表中的客户数据 欢迎使用ServiceStack.Redis或StackExchange.Redis回答。您可以使用高层管理富POCO类型 首先为以下客户获取一个类型化的Red

我在c#Redis缓存中使用了
StackExchange.Redis

cache.StringSet("Key1", CustomerObject);
但我想像这样存储数据

cache.StringSet("Key1", ListOfCustomer);
因此,一个键存储了所有客户列表,并且很容易 搜索、分组、筛选该列表中的客户数据

欢迎使用
ServiceStack.Redis
StackExchange.Redis

回答。您可以使用高层管理富POCO类型

首先为以下客户获取一个类型化的Redis客户端:

var redisCustomers = redis.As<Customer>();
redisCustomers.Lists["Customers"].AddRange(ListOfCustomer);
或具有以下特征的客户列表:

var redisCustomers = redis.As<Customer>();
redisCustomers.Lists["Customers"].AddRange(ListOfCustomer);
如果使用,则可以在其API上使用List方法。 下面是一个简单的IList实现,它使用redis列表存储项目

希望它能帮助您理解一些列表API方法:

public class RedisList<T> : IList<T>
{
    private static ConnectionMultiplexer _cnn;
    private string key;
    public RedisList(string key)
    {
        this.key = key;
        _cnn = ConnectionMultiplexer.Connect("localhost");
    }
    private IDatabase GetRedisDb()
    {
        return _cnn.GetDatabase();
    }
    private string Serialize(object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
    private T Deserialize<T>(string serialized)
    {
        return JsonConvert.DeserializeObject<T>(serialized);
    }
    public void Insert(int index, T item)
    {
        var db = GetRedisDb();
        var before = db.ListGetByIndex(key, index);
        db.ListInsertBefore(key, before, Serialize(item));
    }
    public void RemoveAt(int index)
    {
        var db = GetRedisDb();
        var value = db.ListGetByIndex(key, index);
        if (!value.IsNull)
        {
            db.ListRemove(key, value);
        }
    }
    public T this[int index]
    {
        get
        {
            var value = GetRedisDb().ListGetByIndex(key, index);
            return Deserialize<T>(value.ToString());
        }
        set
        {
            Insert(index, value);
        }
    }
    public void Add(T item)
    {
        GetRedisDb().ListRightPush(key, Serialize(item));
    }
    public void Clear()
    {
        GetRedisDb().KeyDelete(key);
    }
    public bool Contains(T item)
    {
        for (int i = 0; i < Count; i++)
        {
            if (GetRedisDb().ListGetByIndex(key, i).ToString().Equals(Serialize(item)))
            {
                return true;
            }
        }
        return false;
    }
    public void CopyTo(T[] array, int arrayIndex)
    {
        GetRedisDb().ListRange(key).CopyTo(array, arrayIndex);
    }
    public int IndexOf(T item)
    {
        for (int i = 0; i < Count; i++)
        {
            if (GetRedisDb().ListGetByIndex(key, i).ToString().Equals(Serialize(item)))
            {
                return i;
            }
        }
        return -1;
    }
    public int Count
    {
        get { return (int)GetRedisDb().ListLength(key); }
    }
    public bool IsReadOnly
    {
        get { return false; }
    }
    public bool Remove(T item)
    {
        return GetRedisDb().ListRemove(key, Serialize(item)) > 0;
    }
    public IEnumerator<T> GetEnumerator()
    {
        for (int i = 0; i < this.Count; i++)
        {
            yield return Deserialize<T>(GetRedisDb().ListGetByIndex(key, i).ToString());
        }
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        for (int i = 0; i < this.Count; i++)
        {
            yield return Deserialize<T>(GetRedisDb().ListGetByIndex(key, i).ToString());
        }
    }
}
在阅读了您的问题和评论之后,因为您希望通过键访问元素,所以我认为您正在寻找,这是由与值关联的字段组成的映射

因此,您可以拥有一个包含所有客户的哈希的Redis键,每个客户都是与字段关联的值。您可以选择CustomerId作为字段,这样您就可以通过O(1)中的客户id获得客户

我认为实现IDictionary是看到它工作的一个好方法。 因此,与RedisList类似但使用Redis哈希的RedisDictionary类可能是:

public class RedisDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    private static ConnectionMultiplexer _cnn;
    private string _redisKey;
    public RedisDictionary(string redisKey)
    {
        _redisKey = redisKey;
        _cnn = ConnectionMultiplexer.Connect("localhost");
    }
    private IDatabase GetRedisDb()
    {
        return _cnn.GetDatabase();
    }
    private string Serialize(object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
    private T Deserialize<T>(string serialized)
    {
        return JsonConvert.DeserializeObject<T>(serialized);
    }
    public void Add(TKey key, TValue value)
    {
        GetRedisDb().HashSet(_redisKey, Serialize(key), Serialize(value));
    }
    public bool ContainsKey(TKey key)
    {
        return GetRedisDb().HashExists(_redisKey, Serialize(key));
    }
    public bool Remove(TKey key)
    {
        return GetRedisDb().HashDelete(_redisKey, Serialize(key));
    }
    public bool TryGetValue(TKey key, out TValue value)
    {
        var redisValue = GetRedisDb().HashGet(_redisKey, Serialize(key));
        if (redisValue.IsNull)
        {
            value = default(TValue);
            return false;
        }
        value = Deserialize<TValue>(redisValue.ToString());
        return true;
    }
    public ICollection<TValue> Values
    {
        get { return new Collection<TValue>(GetRedisDb().HashValues(_redisKey).Select(h => Deserialize<TValue>(h.ToString())).ToList()); }
    }
    public ICollection<TKey> Keys
    {
        get { return new Collection<TKey>(GetRedisDb().HashKeys(_redisKey).Select(h => Deserialize<TKey>(h.ToString())).ToList()); }
    }
    public TValue this[TKey key]
    {
        get
        {
            var redisValue = GetRedisDb().HashGet(_redisKey, Serialize(key));
            return redisValue.IsNull ? default(TValue) : Deserialize<TValue>(redisValue.ToString());
        }
        set
        {
            Add(key, value);
        }
    }
    public void Add(KeyValuePair<TKey, TValue> item)
    {
        Add(item.Key, item.Value);
    }
    public void Clear()
    {
        GetRedisDb().KeyDelete(_redisKey);
    }
    public bool Contains(KeyValuePair<TKey, TValue> item)
    {
        return GetRedisDb().HashExists(_redisKey, Serialize(item.Key));
    }
    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        GetRedisDb().HashGetAll(_redisKey).CopyTo(array, arrayIndex);
    }
    public int Count
    {
        get { return (int)GetRedisDb().HashLength(_redisKey); }
    }
    public bool IsReadOnly
    {
        get { return false; }
    }
    public bool Remove(KeyValuePair<TKey, TValue> item)
    {
        return Remove(item.Key);
    }
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        var db = GetRedisDb();
        foreach (var hashKey in db.HashKeys(_redisKey))
        {
            var redisValue = db.HashGet(_redisKey, hashKey);
            yield return new KeyValuePair<TKey, TValue>(Deserialize<TKey>(hashKey.ToString()), Deserialize<TValue>(redisValue.ToString()));
        }
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        yield return GetEnumerator();
    }
    public void AddMultiple(IEnumerable<KeyValuePair<TKey, TValue>> items)
    {
        GetRedisDb()
            .HashSet(_redisKey, items.Select(i => new HashEntry(Serialize(i.Key), Serialize(i.Value))).ToArray());
    }
}
公共类字典:IDictionary
{
专用静态连接多路复用器;
私有字符串\u重密钥;
公共RedisDictionary(字符串redisKey)
{
_redisKey=redisKey;
_cnn=ConnectionMultiplexer.Connect(“localhost”);
}
私有IDatabase GetRedisDb()
{
返回_cnn.GetDatabase();
}
私有字符串序列化(对象obj)
{
返回JsonConvert.SerializeObject(obj);
}
私有T反序列化(字符串序列化)
{
返回JsonConvert.DeserializeObject(序列化);
}
公共无效添加(TKey键,TValue值)
{
GetRedisDb().HashSet(_redisKey,Serialize(key),Serialize(value));
}
公共bool ContainsKey(TKey)
{
返回GetRedisDb().HashExists(_redisKey,Serialize(key));
}
公用门移除(TKey)
{
返回GetRedisDb().HashDelete(_redisKey,Serialize(key));
}
公共bool TryGetValue(TKey键,out TValue值)
{
var redisValue=GetRedisDb().HashGet(_redisKey,Serialize(key));
if(redisValue.IsNull)
{
值=默认值(TValue);
返回false;
}
value=反序列化(redisValue.ToString());
返回true;
}
公共ICollection值
{
获取{return new Collection(GetRedisDb().HashValues(_redisKey)。选择(h=>反序列化(h.ToString())).ToList();}
}
公共ICollection密钥
{
获取{return new Collection(GetRedisDb().HashKeys(_redisKey)。选择(h=>反序列化(h.ToString())).ToList();}
}
公共TValue此[TKey]
{
得到
{
var redisValue=GetRedisDb().HashGet(_redisKey,Serialize(key));
return redisValue.IsNull?默认值(TValue):反序列化(redisValue.ToString());
}
设置
{
添加(键、值);
}
}
公共作废添加(KeyValuePair项)
{
添加(item.Key、item.Value);
}
公共空间清除()
{
GetRedisDb().KeyDelete(_redisKey);
}
public bool包含(KeyValuePair项)
{
返回GetRedisDb().HashExists(_redisKey,Serialize(item.Key));
}
public void CopyTo(KeyValuePair[]数组,int-arrayIndex)
{
GetRedisDb().HashGetAll(_redisKey).CopyTo(数组,arrayIndex);
}
公共整数计数
{
get{return(int)GetRedisDb().HashLength(_redisKey);}
}
公共图书馆是只读的
{
获取{return false;}
}
公共布尔删除(KeyValuePair项)
{
返回删除(项.Key);
}
公共IEnumerator GetEnumerator()
{
var db=GetRedisDb();
foreach(db.HashKeys(_redisKey))中的var hashKey)
{
var redisValue=db.HashGet(_redisKey,hashKey);
返回新的KeyValuePair(反序列化(hashKey.ToString()),反序列化(redisValue.ToString());
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
返回GetEnumerator();
}
public void AddMultiple(IEnumerable items)
{
GetRedisDb()
.HashSet(_redisKey,items.Select(i=>newhashentry(Serialize(i.Key),Serialize(i.Value))).ToArray();
}
}
下面是一些使用它的示例:

// Insert customers to the cache            
var customers = new RedisDictionary<int, Customer>("customers");
customers.Add(100, new Customer() { Id = 100, Name = "John" });
customers.Add(200, new Customer() { Id = 200, Name = "Peter" });

// Or if you have a list of customers retrieved from DB:
IList<Customer> customerListFromDb;
customers.AddMultiple(customerListFromDb.ToDictionary(k => k.Id));

// Query a customer by its id
var customers = new RedisDictionary<int, Customer>("customers");
Customer customer100 = customers[100];
//将客户插入缓存
var客户=新的再贴现字典(“客户”);
Add(100,new Customer(){Id=100,Name=“John”});
Add(200,new Customer(){Id=200,Name=“Peter”});
//或者,如果您有从DB检索到的客户列表:
IList customerListFromDb;
AddMultiple(customerListFromDb.ToDictionary(k=>k.Id));
//按客户id查询客户
var客户=新的再贴现字典(“客户”);
客户customer100=客户[100];
更新(2015年10月) 可以在library上找到这些集合的更好实现


是代码。

StackExchange.Redis已经预定义了用于处理列表和值集的函数

获取IDatabase对象:

字符串cacheConnection=Utils.Sections.Storage.RedisCache.ConnectionString

IDatabase cache=ConnectionMultiplexer.Connect(cacheConnection.GetDatabase()

列表方法:

ListLeftPushAsync(键,值)->推送元素列表中的一个

listRangeAncy(key,startIndex,endIndex)->获取值列表

cache.KeyExpire(key,timspan)


有关更多方法,请打包StackExchange.Redis。您不需要包含任何额外的nuget包。

请注意ServiceStack。Redis@thepirat000如何使用ServiceStack使用列表。Redis?取决于