C# Redis辅助类封装与简单聊天室的实现思路说明

虽然redis api的功能比较齐全,但个人觉得为了更好的方便学习和使用,还是很有必有做一个类似DBHelper的帮助类

辅助类主要功能(代码会在最后放出来)

1. 事件监听:
    重新配置广播时(主从同步更改)
    发生内部错误时(调试用)
    更改集群时
    配置更改时
    发生错误时
    物理连接失败时
    建立物理连接时

说明:此处只是进行一个简单的监听,请根据实际需要进行修改

2.存储功能:
    a. 【临时存储】直接 key - value string 类型存储 使用StringXxx方法进行调用
        此类方法用于存储一些临时的、但会被频繁请求到的数据

    b.【永久存储】使用 key - filed - value 类型存储 使用HashXxx方法进行调用
        此类方法存储的是一个类似键值对对象,不必设置有效期,可用于存储一些配置信息

3.消息队列
    【永久存储】 通过push/pop进行消息的读取与存储,可根据实际应用场景制定

4.发布/订阅
    【不进行存储】
    是类似一种即时通讯的功能,可根据实际应用场景制定

为了加深对于redis的使用,就弄了一个简单的通讯功能,这里说下主要的实现思路:

登录时

需要保存用户信息(永久)且设置登录时效(短暂)
a.使用Hash相关方法 添加 用户标识(filed) - Guid(value) key(固定)
b.使用StringXxx相关方法 添加 用户对应的Guid标识 - 固定值 并设置有效时长 

公共聊天室

a.使用Hash相关方法 获取所有Value 获取已登录的用户列表 (由于key 固定 ,每个登录用户获取的都会是同一份列表数据)
b.聊天室实现 (渠道固定+发布订阅)
  事件
    发送消息>
        将消息发布至聊天室渠道
    接收消息>
        订阅聊天室渠道,并将接收的消息显示至消息面板

私聊

a.使用登录用户 与 私聊对象作为参数,生成唯一标识(此处采用md5)
b.使用唯一标识作为聊天渠道进行发布/订阅 进行单人聊天

细节说明

添加提醒相关的发布/订阅(不同提醒根据消息类型进行区分)
  a.登录/退出相关
    1.登录提醒:登录后发布登录提醒,通知其他已登录用户更新已登录用户列表
    2.退出提醒:与1类型
  b.私聊处理
    1.当私聊时发布消息,收到的订阅数为1时(即只有自己订阅了消息),需要将消息添加到消息队列中(使用私聊的唯一标识作为key),并添加一条私聊提示信息,将私聊对象的用户标识作为内容关键字
    2.当在聊天室收到与自己标识相匹配私聊提醒消息时,进行相应提醒
    3.在进入聊天室时,通过生成的标识码,去消息队列获取未读消息并进行显示。

辅助类代码:

public class CusRedisHelper
{

    #region member

    /// <summary>
    /// 连接字符串
    /// </summary>
    protected readonly string ConnectionString;
    /// <summary>
    /// redis 连接对象
    /// </summary>
    protected static IConnectionMultiplexer _connMultiplexer;

    /// <summary>
    /// 默认的key值(用来当作RedisKey的前缀)【此部分为自行修改的,无意义】
    /// </summary>
    public string DefaultKey { get; set; }

    /// <summary>
    /// 锁
    /// </summary>
    private static readonly object Locker = new object();

    /// <summary>
    /// 数据库访问对象
    /// </summary>
    private readonly IDatabase _db;

    /// <summary>
    /// 处理序列化&反序列化
    /// </summary>
    protected IJsonDeal JsonDeal{ get; set; }

    #endregion

    #region constructs

    /// <summary>
    ///
    /// </summary>
    /// <param name="connStr">连接字符串</param>
    /// <param name="defaultKey">默认前缀【无实用】</param>
    /// <param name="db"></param>
    public CusRedisHelper(string connStr, string defaultKey,IJsonDeal jsonDeal, int db = -1)
    {
        this.JsonDeal = jsonDeal;
        //连接字符串
        ConnectionString = connStr;
        //建立连接
        _connMultiplexer = ConnectionMultiplexer.Connect(ConnectionString);
        //默认前缀【无实用】
        DefaultKey = defaultKey;
        //注册相关事件  【未应用】
        RegisterEvent();
        //获取Database操作对象
        _db = _connMultiplexer.GetDatabase(db);
    }

    #endregion

    #region util_method

    /// <summary>
    /// 添加 key 的前缀
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public string AddKeyPrefix(string key)
    {
        return $"{DefaultKey}:{key}";
    }

    #endregion

    #region offer_method

    /// <summary>
    /// 采用双重锁单例模式,保证数据访问对象有且仅有一个
    /// </summary>
    /// <returns></returns>
    public IConnectionMultiplexer GetConnectionRedisMultiplexer()
    {
        if ((_connMultiplexer == null || !_connMultiplexer.IsConnected))
        {
            lock (Locker)
            {
                if ((_connMultiplexer == null || !_connMultiplexer.IsConnected))
                {
                    _connMultiplexer = ConnectionMultiplexer.Connect(ConnectionString);
                }
            }
        }
        return _connMultiplexer;
    }

    public IDatabase GetDataBase()
    {
        return _db;
    }

    /// <summary>
    /// 添加事务处理
    /// </summary>
    /// <returns></returns>
    public ITransaction GetTransaction()
    {
        //创建事务
        return _db.CreateTransaction();
    }

    #endregion

    #region register listener event
    /// <summary>
    /// 注册事件
    /// </summary>
    private static void RegisterEvent()
    {
        _connMultiplexer.ConnectionRestored += ConnMultiplexer_ConnectionRestored;
        _connMultiplexer.ConnectionFailed += ConnMultiplexer_ConnectionFailed;
        _connMultiplexer.ErrorMessage += ConnMultiplexer_ErrorMessage;
        _connMultiplexer.ConfigurationChanged += ConnMultiplexer_ConfigurationChanged;
        _connMultiplexer.HashSlotMoved += ConnMultiplexer_HashSlotMoved;
        _connMultiplexer.InternalError += ConnMultiplexer_InternalError;
        _connMultiplexer.ConfigurationChangedBroadcast += ConnMultiplexer_ConfigurationChangedBroadcast;
    }
    /// <summary>
    /// 重新配置广播时(主从同步更改)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_ConfigurationChangedBroadcast)}: {e.EndPoint}");
    }
    /// <summary>
    /// 发生内部错误时(调试用)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_InternalError(object sender, InternalErrorEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_InternalError)}: {e.Exception}");
    }
    /// <summary>
    /// 更改集群时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_HashSlotMoved(object sender, HashSlotMovedEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_HashSlotMoved)}: {nameof(e.OldEndPoint)}-{e.OldEndPoint} To {nameof(e.NewEndPoint)}-{e.NewEndPoint} ");
    }
    /// <summary>
    /// 配置更改时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_ConfigurationChanged(object sender, EndPointEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_ConfigurationChanged)}: {e.EndPoint}");
    }
    /// <summary>
    /// 发生错误时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_ErrorMessage(object sender, RedisErrorEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_ErrorMessage)}: {e.Message}");
    }
    /// <summary>
    /// 物理连接失败时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_ConnectionFailed)}: {e.Exception}");
    }
    /// <summary>
    /// 建立物理连接时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void ConnMultiplexer_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
    {
        Console.WriteLine($"{nameof(ConnMultiplexer_ConnectionRestored)}: {e.Exception}");
    }
    #endregion

    #region stringGet
    /// <summary>
    /// 设置key,并保存字符串(如果key 已存在,则覆盖)
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <param name="expried"></param>
    /// <returns></returns>
    public bool StringSet(string redisKey, string redisValue, TimeSpan? expried = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.StringSet(redisKey, redisValue, expried);
    }
    /// <summary>
    /// 保存多个key-value
    /// </summary>
    /// <param name="keyValuePairs"></param>
    /// <returns></returns>
    public bool StringSet(IEnumerable<KeyValuePair<RedisKey, RedisValue>> keyValuePairs)
    {
        keyValuePairs =
            keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(AddKeyPrefix(x.Key), x.Value));
        return _db.StringSet(keyValuePairs.ToArray());
    }
    /// <summary>
    /// 获取字符串
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public string StringGet(string redisKey, TimeSpan? expired = null)
    {
        try
        {
            redisKey = AddKeyPrefix(redisKey);
            return _db.StringGet(redisKey);
        }
        catch (TypeAccessException ex)
        {
            throw ex;
        }
    }
    /// <summary>
    /// 存储一个对象,该对象会被序列化存储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public bool StringSet<T>(string redisKey, T redisValue, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        var json = JsonDeal.Serialize(redisKey);
        return _db.StringSet(redisKey, json, expired);
    }
    /// <summary>
    /// 获取一个对象(会进行反序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public T StringGet<T>(string redisKey, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        return JsonDeal.Deserialize<T>(_db.StringGet(redisKey));
    }

    /// <summary>
    /// 保存一个字符串值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public async Task<bool> StringSetAsync(string redisKey, string redisValue, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.StringSetAsync(redisKey, redisValue, expired);
    }
    /// <summary>
    /// 保存一个字符串值
    /// </summary>
    /// <param name="keyValuePairs"></param>
    /// <returns></returns>
    public async Task<bool> StringSetAsync(IEnumerable<KeyValuePair<RedisKey, RedisValue>> keyValuePairs)
    {
        keyValuePairs
            = keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(AddKeyPrefix(x.Key), x.Value));
        return await _db.StringSetAsync(keyValuePairs.ToArray());
    }
    /// <summary>
    /// 获取单个值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public async Task<string> StringGetAsync(string redisKey, string redisValue, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.StringGetAsync(redisKey);
    }
    /// <summary>
    /// 存储一个对象(该对象会被序列化保存)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public async Task<bool> StringSetAsync<T>(string redisKey, string redisValue, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        var json = JsonDeal.Serialize(redisValue);
        return await _db.StringSetAsync(redisKey, json, expired);
    }
    /// <summary>
    /// 获取一个对象(反序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public async Task<T> StringGetAsync<T>(string redisKey, string redisValue, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        return JsonDeal.Deserialize<T>(await _db.StringGetAsync(redisKey));
    }
    #endregion

    #region  Hash operation  Hast 存储  >>> redisKey:{hashField:value}

    /// <summary>
    /// 判断字段是否在hash中
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public bool HashExist(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashExists(redisKey, hashField);
    }
    /// <summary>
    /// 从hash 中删除字段
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public bool HashDelete(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashDelete(redisKey, hashField);
    }
    /// <summary>
    /// 从hash中移除指定字段
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public long HashDelete(string redisKey, IEnumerable<RedisValue> hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashDelete(redisKey, hashField.ToArray());
    }
    /// <summary>
    /// 在hash中设定值 存储示例
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool HashSet(string redisKey, string hashField, string value)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashSet(redisKey, hashField, value);
    }
    /// <summary>
    /// 从Hash 中获取值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public RedisValue HashGet(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashGet(redisKey, hashField);
    }
    /// <summary>
    /// 从Hash 中获取值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public RedisValue[] HashGet(string redisKey, RedisValue[] hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashGet(redisKey, hashField);
    }
    /// <summary>
    /// 从hash 返回所有的key值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public IEnumerable<RedisValue> HashKeys(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashKeys(redisKey);
    }
    /// <summary>
    /// 根据key返回hash中的值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public RedisValue[] HashValues(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.HashValues(redisKey);
    }
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool HashSet<T>(string redisKey, string hashField, T value)
    {
        redisKey = AddKeyPrefix(redisKey);
        var json = JsonDeal.Serialize(value);
        return _db.HashSet(redisKey, hashField, json);
    }
    /// <summary>
    /// 在hash 中获取值 (反序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public T HashGet<T>(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return JsonDeal.Deserialize<T>(_db.HashGet(redisKey, hashField));
    }
    /// <summary>
    /// 判断字段是否存在hash 中
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public async Task<bool> HashExistsAsync(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashExistsAsync(redisKey, hashField);
    }
    /// <summary>
    /// 从hash中移除指定字段
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public async Task<bool> HashDeleteAsync(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashDeleteAsync(redisKey, hashField);
    }
    /// <summary>
    /// 从hash中移除指定字段
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public async Task<long> HashDeleteAsync(string redisKey, IEnumerable<RedisValue> hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashDeleteAsync(redisKey, hashField.ToArray());
    }
    /// <summary>
    /// 在hash 设置值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public async Task<bool> HashSetAsync(string redisKey, string hashField, string value)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashSetAsync(redisKey, hashField, value);
    }
    /// <summary>
    /// 在hash 中设定值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashFields"></param>
    /// <returns></returns>
    public async Task HashSetAsync(string redisKey, IEnumerable<HashEntry> hashFields)
    {
        redisKey = AddKeyPrefix(redisKey);
        await _db.HashSetAsync(redisKey, hashFields.ToArray());
    }
    /// <summary>
    /// 在hash 中设定值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public async Task<RedisValue> HashGetAsync(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashGetAsync(redisKey, hashField);
    }
    /// <summary>
    /// 在hash 中获取值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public async Task<IEnumerable<RedisValue>> HashGetAsync(string redisKey, RedisValue[] hashField, string value)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashGetAsync(redisKey, hashField);
    }
    /// <summary>
    /// 从hash返回所有的字段值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<IEnumerable<RedisValue>> HashKeysAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashKeysAsync(redisKey);
    }
    /// <summary>
    /// 返回hash中所有的值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<IEnumerable<RedisValue>> HashValuesAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.HashValuesAsync(redisKey);
    }
    /// <summary>
    /// 在hash 中设定值(序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public async Task<bool> HashSetAsync<T>(string redisKey, string hashField, T value)
    {
        redisKey = AddKeyPrefix(redisKey);
        var json = JsonDeal.Serialize(value);
        return await _db.HashSetAsync(redisKey, hashField, json);
    }
    /// <summary>
    /// 在hash中获取值(反序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="hashField"></param>
    /// <returns></returns>
    public async Task<T> HashGetAsync<T>(string redisKey, string hashField)
    {
        redisKey = AddKeyPrefix(redisKey);
        return JsonDeal.Deserialize<T>(await _db.HashGetAsync(redisKey, hashField));
    }
    #endregion

    #region queue list operation
    /// <summary>
    /// 移除并返回key所对应列表的第一个元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public string ListLeftPop(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListLeftPop(redisKey);
    }
    /// <summary>
    /// 移除并返回key所对应列表的最后一个元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public string ListRightPop(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListRightPop(redisKey);
    }
    /// <summary>
    /// 移除指定key及key所对应的元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public long ListRemove(string redisKey, string redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListRemove(redisKey, redisValue);
    }
    /// <summary>
    /// 在列表尾部插入值,如果键不存在,先创建再插入值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public long ListRightPush(string redisKey, string redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListRightPush(redisKey, redisValue);
    }
    /// <summary>
    /// 在列表头部插入值,如果键不存在,先创建再插入值
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public long ListLeftPush(string redisKey, string redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListLeftPush(redisKey, redisValue);
    }
    /// <summary>
    /// 返回列表上该键的长度,如果不存在,返回0
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public long ListLength(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListLength(redisKey);
    }
    /// <summary>
    /// 返回在该列表上键所对应的元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public IEnumerable<RedisValue> ListRange(string redisKey)
    {
        try
        {
            redisKey = AddKeyPrefix(redisKey);
            return _db.ListRange(redisKey);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    /// <summary>
    /// 移除并返回存储在该键列表的第一个元素
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public T ListLeftPop<T>(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        var redisValue = _db.ListLeftPop(redisKey);
        return JsonDeal.Deserialize<T>(redisValue);
    }
    /// <summary>
    /// 移除并返回该列表上的最后一个元素
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public T ListRightPop<T>(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        var redisValue = _db.ListRightPop(redisKey);
        return JsonDeal.Deserialize<T>(redisValue);
    }
    /// <summary>
    /// 在列表尾部插入值,如果键不存在,先创建再插入值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public long ListRightPush<T>(string redisKey, T redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListRightPush(redisKey, JsonDeal.Serialize(redisValue));
    }
    /// <summary>
    /// 在列表头部插入值,如果键不存在,创建后插入值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public long ListLeftPush<T>(string redisKey, T redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.ListLeftPush(redisKey, JsonDeal.Serialize(redisValue));
    }
    /// <summary>
    /// 移除并返回存储在该键列表的第一个元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<string> ListLeftPopAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListLeftPopAsync(redisKey);
    }
    /// <summary>
    /// 移除并返回存储在该键列表的最后一个元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<string> ListRightPopAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListRightPopAsync(redisKey);
    }
    /// <summary>
    /// 移除列表指定键上与值相同的元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<long> ListRemoveAsync(string redisKey, string redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListRemoveAsync(redisKey, redisValue);
    }
    /// <summary>
    /// 在列表尾部差入值,如果键不存在,先创建后插入
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public async Task<long> ListRightPushAsync(string redisKey, string redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListRightPushAsync(redisKey, redisValue);
    }
    /// <summary>
    /// 在列表头部插入值,如果键不存在,先创建后插入
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public async Task<long> ListLeftPushAsync(string redisKey, string redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListLeftPushAsync(redisKey, redisValue);
    }
    /// <summary>
    /// 返回列表上的长度,如果不存在,返回0
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<long> ListLengthAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListLengthAsync(redisKey);
    }
    /// <summary>
    /// 返回在列表上键对应的元素
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<IEnumerable<RedisValue>> ListRangeAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListRangeAsync(redisKey);
    }
    /// <summary>
    /// 移除并返回存储在key对应列表的第一个元素
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<T> ListLeftPopAsync<T>(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return JsonDeal.Deserialize<T>(await _db.ListLeftPopAsync(redisKey));
    }
    /// <summary>
    /// 移除并返回存储在key 对应列表的最后一个元素
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<T> ListRightPopAsync<T>(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return JsonDeal.Deserialize<T>(await _db.ListRightPopAsync(redisKey));
    }
    /// <summary>
    /// 在列表尾部插入值,如果值不存在,先创建后写入值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public async Task<long> ListRightPushAsync<T>(string redisKey, T redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListRightPushAsync(redisKey, JsonDeal.Serialize(redisValue));
    }
    /// <summary>
    /// 在列表头部插入值,如果值不存在,先创建后写入值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="redisValue"></param>
    /// <returns></returns>
    public async Task<long> ListLeftPushAsync<T>(string redisKey, T redisValue)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.ListLeftPushAsync(redisKey, JsonDeal.Serialize(redisValue));
    }
    #endregion

    #region sorted set operation
    /// <summary>
    /// sortedset 新增
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="member"></param>
    /// <param name="score"></param>
    /// <returns></returns>
    public bool SortedSetAdd(string redisKey, string member, double score)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.SortedSetAdd(redisKey, member, score);
    }
    /// <summary>
    /// 在有序集合中返回指定范围的元素,默认情况下由低到高
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public IEnumerable<RedisValue> SortedSetRangeByRank(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.SortedSetRangeByRank(redisKey);
    }
    /// <summary>
    /// 返回有序集合的个数
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public long SortedSetLength(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.SortedSetLength(redisKey);
    }
    /// <summary>
    /// 返回有序集合的元素个数
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="member"></param>
    /// <returns></returns>
    public bool SortedSetLength(string redisKey, string member)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.SortedSetRemove(redisKey, member);
    }
    /// <summary>
    ///  sorted set Add
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="member"></param>
    /// <param name="score"></param>
    /// <returns></returns>
    public bool SortedSetAdd<T>(string redisKey, T member, double score)
    {
        redisKey = AddKeyPrefix(redisKey);
        var json = JsonDeal.Serialize(member);
        return _db.SortedSetAdd(redisKey, json, score);
    }
    /// <summary>
    /// sorted set add
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="member"></param>
    /// <param name="score"></param>
    /// <returns></returns>
    public async Task<bool> SortedSetAddAsync(string redisKey, string member, double score)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.SortedSetAddAsync(redisKey, member, score);
    }
    /// <summary>
    /// 在有序集合中返回指定范围的元素,默认情况下由低到高
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<IEnumerable<RedisValue>> SortedSetRangeByRankAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.SortedSetRangeByRankAsync(redisKey);
    }
    /// <summary>
    /// 返回有序集合的元素个数
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<long> SortedSetLengthAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.SortedSetLengthAsync(redisKey);
    }
    /// <summary>
    /// 返回有序集合的元素个数
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="member"></param>
    /// <returns></returns>
    public async Task<bool> SortedSetRemoveAsync(string redisKey, string member)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.SortedSetRemoveAsync(redisKey, member);
    }
    /// <summary>
    /// SortedSet 新增
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisKey"></param>
    /// <param name="member"></param>
    /// <param name="score"></param>
    /// <returns></returns>
    public async Task<bool> SortedSetAddAsync<T>(string redisKey, T member, double score)
    {
        redisKey = AddKeyPrefix(redisKey);
        var json = JsonDeal.Serialize(member);
        return await _db.SortedSetAddAsync(redisKey, json, score);
    }

    #endregion

    #region key operation
    /// <summary>
    /// 移除指定key
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public bool KeyDelete(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.KeyDelete(redisKey);
    }
    /// <summary>
    /// 删除指定key
    /// </summary>
    /// <param name="redisKeys"></param>
    /// <returns></returns>
    public long KeyDelete(IEnumerable<string> redisKeys)
    {
        var keys = redisKeys.Select(x => (RedisKey)AddKeyPrefix(x));
        return _db.KeyDelete(keys.ToArray());
    }
    /// <summary>
    /// 检验key是否存在
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public bool KeyExists(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.KeyExists(redisKey);
    }
    /// <summary>
    /// 重命名key
    /// </summary>
    /// <param name="oldKeyName"></param>
    /// <param name="newKeyName"></param>
    /// <returns></returns>
    public bool KeyReName(string oldKeyName, string newKeyName)
    {
        oldKeyName = AddKeyPrefix(oldKeyName);
        return _db.KeyRename(oldKeyName, newKeyName);
    }
    /// <summary>
    /// 设置key 的过期时间
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public bool KeyExpire(string redisKey, TimeSpan? expired = null)
    {
        redisKey = AddKeyPrefix(redisKey);
        return _db.KeyExpire(redisKey, expired);
    }
    /// <summary>
    /// 移除指定的key
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<bool> KeyDeleteAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.KeyDeleteAsync(redisKey);
    }
    /// <summary>
    /// 删除指定的key
    /// </summary>
    /// <param name="redisKeys"></param>
    /// <returns></returns>
    public async Task<long> KeyDeleteAsync(IEnumerable<string> redisKeys)
    {
        var keys = redisKeys.Select(x => (RedisKey)AddKeyPrefix(x));
        return await _db.KeyDeleteAsync(keys.ToArray());
    }
    /// <summary>
    /// 检验key 是否存在
    /// </summary>
    /// <param name="redisKey"></param>
    /// <returns></returns>
    public async Task<bool> KeyExistsAsync(string redisKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.KeyExistsAsync(redisKey);
    }
    /// <summary>
    /// 重命名key
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="redisNewKey"></param>
    /// <returns></returns>
    public async Task<bool> KeyRenameAsync(string redisKey, string redisNewKey)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.KeyRenameAsync(redisKey, redisNewKey);
    }
    /// <summary>
    /// 设置 key 时间
    /// </summary>
    /// <param name="redisKey"></param>
    /// <param name="expired"></param>
    /// <returns></returns>
    public async Task<bool> KeyExpireAsync(string redisKey, TimeSpan? expired)
    {
        redisKey = AddKeyPrefix(redisKey);
        return await _db.KeyExpireAsync(redisKey, expired);
    }
    #endregion

    #region Publish And Subscribe
    /// <summary>
    /// 订阅
    /// </summary>
    /// <param name="channel">频道</param>
    /// <param name="handle">事件</param>
    public void Subscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handle)
    {
        //getSubscriber() 获取到指定服务器的发布者订阅者的连接
        var sub = _connMultiplexer.GetSubscriber();
        //订阅执行某些操作时改变了 优先/主动 节点广播
        sub.Subscribe(channel, handle);
    }

    /// <summary>
    /// 取消订阅
    /// </summary>
    /// <param name="channel">频道</param>
    /// <param name="handle">事件</param>
    public void UnSubscribe(RedisChannel channel, Action<RedisChannel, RedisValue> handle)
    {
        //getSubscriber() 获取到指定服务器的发布者订阅者的连接
        var sub = _connMultiplexer.GetSubscriber();
        //订阅执行某些操作时改变了 优先/主动 节点广播
        sub.Unsubscribe(channel, handle);
    }

    /// <summary>
    /// 取消订阅
    /// </summary>
    /// <param name="channel">频道</param>
    /// <param name="handle">事件</param>
    public async Task UnSubscribeAsync(RedisChannel channel, Action<RedisChannel, RedisValue> handle)
    {
        //getSubscriber() 获取到指定服务器的发布者订阅者的连接
        var sub = _connMultiplexer.GetSubscriber();
        //订阅执行某些操作时改变了 优先/主动 节点广播
        await sub.UnsubscribeAsync(channel, handle);
    }

    /// <summary>
    /// 发布
    /// </summary>
    /// <param name="channel"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public long Publish(RedisChannel channel, RedisValue message)
    {
        var sub = _connMultiplexer.GetSubscriber();
        return sub.Publish(channel, message);
    }
    /// <summary>
    /// 发布(使用序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="channel"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public long Publish<T>(RedisChannel channel, T message)
    {
        var sub = _connMultiplexer.GetSubscriber();
        return sub.Publish(channel, JsonDeal.Serialize(message));
    }
    /// <summary>
    /// 订阅
    /// </summary>
    /// <param name="redisChannel"></param>
    /// <param name="handle"></param>
    /// <returns></returns>
    public async Task SubscribeAsync(RedisChannel redisChannel, Action<RedisChannel, RedisValue> handle)
    {
        var sub = _connMultiplexer.GetSubscriber();
        await sub.SubscribeAsync(redisChannel, handle);
    }
    /// <summary>
    /// 发布
    /// </summary>
    /// <param name="redisChannel"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public async Task<long> PublishAsync(RedisChannel redisChannel, RedisValue message)
    {
        var sub = _connMultiplexer.GetSubscriber();
        return await sub.PublishAsync(redisChannel, message);
    }
    /// <summary>
    /// 发布(使用序列化)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="redisChannel"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public async Task<long> PublishAsync<T>(RedisChannel redisChannel, T message)
    {
        var sub = _connMultiplexer.GetSubscriber();
        return await sub.PublishAsync(redisChannel, JsonDeal.Serialize(message));
    }
    #endregion

}

《接口(实现根据场景自己实现吧:) 我是使用Newtonsoft.Json简单的实现了一下)》

public interface IJsonDeal
{

    string Serialize(object obj);

    T Deserialize<T>(string jsonDate);

}

辅助类的大部分都是参考其他大佬的博文

https://www.cnblogs.com/monster17/p/9283898.html



author:monster

since:7/10/2018 5:33:22 PM

direction:redis helper

原文地址:https://www.cnblogs.com/monster17/p/9290653.html

时间: 2024-10-11 01:30:00

C# Redis辅助类封装与简单聊天室的实现思路说明的相关文章

使用socket.io+redis来实现基本的聊天室应用场景

本文根据socket.io与redis来实现基本的聊天室应用场景,主要表现于多个浏览器之间的信息同步和实时更新. 首先看下基本的应用场景:多个浏览器同时跟webServer连接,可实时获取webServer推送的数据,如显示某一项实时更新的数据,多个client之间同步消息等. 这里,需要使用到socket.io和redis的publish机制. 1, socket.io连接于浏览器和nodejs的http服务器之间,可用于二者之间同步数据. 2, redis是一种key-value的数据库,可

Python Socket 简单聊天室2

上篇文章写了一个简单的单线程的一问一答的简单聊天室.这次我们使用SocketServer模块搭建一个多线程异步的聊天室. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 # -*- coding:utf-8 -*- import SocketServer class  mysocketclass(SocketServer.BaseRequestHandler):     def handle(self):         client_inform

ASP.NET 使用application和session对象写的简单聊天室程序

ASP.Net中有两个重要的对象,一个是application对象,一个是session对象. Application:记录应用程序参数的对象,该对象用于共享应用程序级信息. Session:记录浏览器端的变量对象,用来存储跨网页程序程序的变量或者对象. 说实话,写了快一年的asp.net,application对象还真没怎么用过.看了看书,根据这两个对象的特性写了一个简单的聊天室程序.真的是非常的简陋. 我的思路是,有两个页面Default页和ChatRoom页,页面布局如图: Default

C#实例之简单聊天室(状态管理)

前言        状态管理是在同一页或不同页的多个请求发生时,维护状态和页信息的过程.因为Web应用程序的通信协议使用了无状态的HTTP协议,所以当客户端请求页面时,ASP.NET服务器端都会重新生成一个网页实例.此时,旧网页的任务完成,旧网页的实例也随之消失.这种无状态,意味着客户端用户在浏览器中的一些状态或是对数据的一些修改都将丢失. 为了弥补这种基于web应用程序的固有限制,ASP.NET提供了多种用于管理状态的功能. 简单聊天室 这里运用System.Web命名空间的那些管理状态的类,

基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍。最后我们将会实现一个基于Server-Sent Event和Flask简单的在线聊天室。

基于Server-Sent Event的简单聊天室 Web 2.0时代,即时通信已经成为必不可少的网站功能,那实现Web即时通信的机制有哪些呢?在这门项目课中我们将一一介绍.最后我们将会实现一个基于Server-Sent Event和Flask简单的在线聊天室.

Asp.Net SignalR - 简单聊天室实现

原文:Asp.Net SignalR - 简单聊天室实现 简单聊天室 使用持久链接类我们就可以做一些即时通讯的应用了,我使用Group做了一个简单的聊天室,先上图技术细节下面再讲 可以加入聊天室.创建聊天室.发送消息,下面就说说我是如何通过Group做出来的 持久链接类有一个Groups的对象,通过这个对象,我们可以进行分组添加人员.发送消息.删除人员等操作 在连接事件中,给当前游客指定随机名称,并且返回当前已有的聊天室信息 protected override Task OnConnected

Java简单聊天室

实现Java简单的聊天室 所用主要知识:多线程+网络编程 效果如下图 /** * * @author Administrator * * 简单的多人聊天系统——重点:同时性,异步性 * 1.客户端:发送消息,并且接收消息 * 1.1 消息发送至服务器:服务器每次都将客户发过来的信息发送到每个客户端 * 1.2 接收消息:发送的同时也要接收消息,所以必须有两个线程,一个发送消息,一个接收消息 * 1.3 关于这两个线程:如果没有线程,接收和发送就是按顺序执行的了,那么是发送后接收还是接收后发送?或

asp.net mvc signalr 简单聊天室

signalr的神奇.实用很早就知道,但一直都没有亲自去试用,仅停留在文章,看了几篇简单的介绍文字,感觉还是很简单易用的. 由于最后有个项目需要使用到它,所以就决定写个小程序测试一下,实践出真知:别人写的文章,由于环境(版本等)不同,还是或多或少存在一些出入的. 环境:vs2013 / asp.net mvc 5 / signalr 2.2.1 / jquery 1.10.2 先上两个效果图: 系统会自动给加入聊天室的人员分配一个ID,是该人员的唯一标识(绿色为当前用户说的话,橙色为当前用户之外

用swoole和websocket开发简单聊天室

首先,我想说下写代码的一些习惯,第一,任何可配置的参数或变量都要写到一个config文件中.第二,代码中一定要有日志记录和完善的报错并记录报错.言归正传,swoole应该是每个phper必须要了解的,它号称重新定义了php.此聊天室利用了swoole高并发并且异步非阻塞的特点提高了程序的性能. 首先,定义一个 swoole_lock 和 swoole_websocket_server ,并且配置参数,具体参数详情可以去swoole官网查看. public function start(){ $t