Redis—.Net中的使用
来源:http://www.cnblogs.com/qtqq/p/5951201.html,https://www.cnblogs.com/xsj1989/p/9104185.html
Redis安装:http://www.runoob.com/redis/redis-install.html
Configuration:https://www.cnblogs.com/ArvinZhao/p/6007043.html
Redis可视化工具Redis Desktop Manager:https://redisdesktop.com/download
千万要记住,给Redis设置访问密码,Redis的连接字符串中也要设置好密码。
Redis设置密码:https://blog.csdn.net/qq_35357001/article/details/56835919
启动服务:dos中 cd Redis安装目录,运行 redis-server.exe redis.windows.conf;
启动命令:dos中 cd Redis安装目录,运行 redis-cli.exe -h 127.0.0.1 -p 6379;
设置密码:config set requirepass xsj10011 注意:密码尽量设置长一点
获取密码:config get requirepass 注意:获取密码之前需要先验证密码,不然获取不到
验证密码:auth xsj10011
密码改变之后,代码中的连接字符串里的密码也要对应改变,不然操作不了Redis。对应的可视化工具里的密码也要改。
1.打开VS的NuGet》搜索:StackExchange.Redis,安装到项目中
2.配置文件:
<appSettings>
<!-- 系统前缀 -->
<add key="redisKey" value="jay"/>
</appSettings>
<connectionStrings>
<!-- Redis连接字符串 -->
<add name="RedisExchangeHosts" connectionString="127.0.0.1:6379,allowadmin=true,password=xsj10011,keepAlive=180"/>
</connectionStrings>
web.config
3.封装好的Redis操作类(感谢前辈的努力,让我们可以直接拿来用,恕我懒惰):
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web; namespace RedisTest.RedisCommon
{
/// <summary>
/// ConnectionMultiplexer对象管理帮助类
/// </summary>
public static class RedisConnectionHelp
{
//配置:系统自定义Key前缀
public static readonly string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? "";
//配置:Redis连接字符串:127.0.0.1:6379,allowadmin=true
private static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString; private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>(); /// <summary>
/// 单例获取
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
} /// <summary>
/// 缓存获取
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
{
if (!ConnectionCache.ContainsKey(connectionString))
{
ConnectionCache[connectionString] = GetManager(connectionString);
}
return ConnectionCache[connectionString];
} private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisConnectionString;
var connect = ConnectionMultiplexer.Connect(connectionString); //注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError; return connect;
} #region 事件 /// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
} /// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine("ErrorMessage: " + e.Message);
} /// <summary>
/// 重新建立连接之前的错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("ConnectionRestored: " + e.EndPoint);
} /// <summary>
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
} /// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
} /// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine("InternalError:Message" + e.Exception.Message);
} #endregion 事件
}
}
RedisConnectionHelp
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web; namespace RedisTest.RedisCommon
{
public class RedisHelper
{
private int DbNum { get; }
private readonly ConnectionMultiplexer _conn;
public string CustomKey; #region 构造函数 public RedisHelper(int dbNum = )
: this(dbNum, null)
{
} public RedisHelper(int dbNum, string readWriteHosts)
{
DbNum = dbNum;
_conn =
string.IsNullOrWhiteSpace(readWriteHosts) ?
RedisConnectionHelp.Instance :
RedisConnectionHelp.GetConnectionMultiplexer(readWriteHosts);
}
#endregion #region 辅助方法 private string AddSysCustomKey(string oldKey)
{
var prefixKey = CustomKey ?? RedisConnectionHelp.SysCustomKey;
return prefixKey + oldKey;
} private T Do<T>(Func<IDatabase, T> func)
{
var database = _conn.GetDatabase(DbNum);
return func(database);
} private string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
} private T ConvertObj<T>(RedisValue value)
{
return JsonConvert.DeserializeObject<T>(value);
} private List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
} private RedisKey[] ConvertRedisKeys(List<string> redisKeys)
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
} #endregion 辅助方法 #region String #region 同步方法 /// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.StringSet(key, value, expiry));
} /// <summary>
/// 保存多个key value
/// </summary>
/// <param name="keyValues">键值对</param>
/// <returns></returns>
public bool StringSet(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return Do(db => db.StringSet(newkeyValues.ToArray()));
} /// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool StringSet<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return Do(db => db.StringSet(key, json, expiry));
} /// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public string StringGet(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.StringGet(key));
} /// <summary>
/// 获取多个Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public RedisValue[] StringGet(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return Do(db => db.StringGet(ConvertRedisKeys(newKeys)));
} /// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T StringGet<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db => ConvertObj<T>(db.StringGet(key)));
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public double StringIncrement(string key, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.StringIncrement(key, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public double StringDecrement(string key, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.StringDecrement(key, val));
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await Do(db => db.StringSetAsync(key, value, expiry));
} /// <summary>
/// 保存多个key value
/// </summary>
/// <param name="keyValues">键值对</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return await Do(db => db.StringSetAsync(newkeyValues.ToArray()));
} /// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return await Do(db => db.StringSetAsync(key, json, expiry));
} /// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public async Task<string> StringGetAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringGetAsync(key));
} /// <summary>
/// 获取多个Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public async Task<RedisValue[]> StringGetAsync(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys)));
} /// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> StringGetAsync<T>(string key)
{
key = AddSysCustomKey(key);
string result = await Do(db => db.StringGetAsync(key));
return ConvertObj<T>(result);
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public async Task<double> StringIncrementAsync(string key, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.StringIncrementAsync(key, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public async Task<double> StringDecrementAsync(string key, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.StringDecrementAsync(key, val));
} #endregion 异步方法 #endregion String #region List #region 同步方法 /// <summary>
/// 移除指定ListId的内部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRemove(key, ConvertJson(value)));
} /// <summary>
/// 获取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> ListRange<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvetList<T>(values);
});
} /// <summary>
/// 入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRightPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRightPush(key, ConvertJson(value)));
} /// <summary>
/// 出队
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListRightPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return ConvertObj<T>(value);
});
} /// <summary>
/// 入栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListLeftPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListLeftPush(key, ConvertJson(value)));
} /// <summary>
/// 出栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListLeftPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListLeftPop(key);
return ConvertObj<T>(value);
});
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long ListLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.ListLength(key));
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 移除指定ListId的内部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRemoveAsync(key, ConvertJson(value)));
} /// <summary>
/// 获取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> ListRangeAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.ListRangeAsync(key));
return ConvetList<T>(values);
} /// <summary>
/// 入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRightPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRightPushAsync(key, ConvertJson(value)));
} /// <summary>
/// 出队
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListRightPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListRightPopAsync(key));
return ConvertObj<T>(value);
} /// <summary>
/// 入栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListLeftPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value)));
} /// <summary>
/// 出栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListLeftPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListLeftPopAsync(key));
return ConvertObj<T>(value);
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> ListLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.ListLengthAsync(key));
} #endregion 异步方法 #endregion List #region Hash #region 同步方法 /// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashExists(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashExists(key, dataKey));
} /// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool HashSet<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string json = ConvertJson(t);
return db.HashSet(key, dataKey, json);
});
} /// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashDelete(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDelete(key, dataKey));
} /// <summary>
/// 移除hash中的多个值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public long HashDelete(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return Do(db => db.HashDelete(key, dataKeys.ToArray()));
} /// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public T HashGet<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return ConvertObj<T>(value);
});
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public double HashIncrement(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.HashIncrement(key, dataKey, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public double HashDecrement(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.HashDecrement(key, dataKey, val));
} /// <summary>
/// 获取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> HashKeys<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
RedisValue[] values = db.HashKeys(key);
return ConvetList<T>(values);
});
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashExistsAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashExistsAsync(key, dataKey));
} /// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return await Do(db =>
{
string json = ConvertJson(t);
return db.HashSetAsync(key, dataKey, json);
});
} /// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashDeleteAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDeleteAsync(key, dataKey));
} /// <summary>
/// 移除hash中的多个值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray()));
} /// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<T> HashGeAsync<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = await Do(db => db.HashGetAsync(key, dataKey));
return ConvertObj<T>(value);
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public async Task<double> HashIncrementAsync(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.HashIncrementAsync(key, dataKey, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public async Task<double> HashDecrementAsync(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDecrementAsync(key, dataKey, val));
} /// <summary>
/// 获取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> HashKeysAsync<T>(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = await Do(db => db.HashKeysAsync(key));
return ConvetList<T>(values);
} #endregion 异步方法 #endregion Hash #region SortedSet 有序集合 #region 同步方法 /// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public bool SortedSetAdd<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetAdd(key, ConvertJson<T>(value), score));
} /// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public bool SortedSetRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetRemove(key, ConvertJson(value)));
} /// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> SortedSetRangeByRank<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SortedSetRangeByRank(key);
return ConvetList<T>(values);
});
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long SortedSetLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetLength(key));
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public async Task<bool> SortedSetAddAsync<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson<T>(value), score));
} /// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<bool> SortedSetRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value)));
} /// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.SortedSetRangeByRankAsync(key));
return ConvetList<T>(values);
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> SortedSetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetLengthAsync(key));
} #endregion 异步方法 #endregion SortedSet 有序集合 #region key /// <summary>
/// 删除单个key
/// </summary>
/// <param name="key">redis key</param>
/// <returns>是否删除成功</returns>
public bool KeyDelete(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyDelete(key));
} /// <summary>
/// 删除多个key
/// </summary>
/// <param name="keys">rediskey</param>
/// <returns>成功删除的个数</returns>
public long KeyDelete(List<string> keys)
{
List<string> newKeys = keys.Select(AddSysCustomKey).ToList();
return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys)));
} /// <summary>
/// 判断key是否存储
/// </summary>
/// <param name="key">redis key</param>
/// <returns></returns>
public bool KeyExists(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExists(key));
} /// <summary>
/// 重新命名key
/// </summary>
/// <param name="key">就的redis key</param>
/// <param name="newKey">新的redis key</param>
/// <returns></returns>
public bool KeyRename(string key, string newKey)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyRename(key, newKey));
} /// <summary>
/// 设置Key的时间
/// </summary>
/// <param name="key">redis key</param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExpire(key, expiry));
} #endregion key #region 发布订阅 /// <summary>
/// Redis发布订阅 订阅
/// </summary>
/// <param name="subChannel"></param>
/// <param name="handler"></param>
public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Subscribe(subChannel, (channel, message) =>
{
if (handler == null)
{
Console.WriteLine(subChannel + " 订阅收到消息:" + message);
}
else
{
handler(channel, message);
}
});
} /// <summary>
/// Redis发布订阅 发布
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel"></param>
/// <param name="msg"></param>
/// <returns></returns>
public long Publish<T>(string channel, T msg)
{
ISubscriber sub = _conn.GetSubscriber();
return sub.Publish(channel, ConvertJson(msg));
} /// <summary>
/// Redis发布订阅 取消订阅
/// </summary>
/// <param name="channel"></param>
public void Unsubscribe(string channel)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Unsubscribe(channel);
} /// <summary>
/// Redis发布订阅 取消全部订阅
/// </summary>
public void UnsubscribeAll()
{
ISubscriber sub = _conn.GetSubscriber();
sub.UnsubscribeAll();
} #endregion 发布订阅 #region 其他 public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
} public IDatabase GetDatabase()
{
return _conn.GetDatabase(DbNum);
} public IServer GetServer(string hostAndPort)
{
return _conn.GetServer(hostAndPort);
} /// <summary>
/// 设置前缀
/// </summary>
/// <param name="customKey"></param>
public void SetSysCustomKey(string customKey)
{
CustomKey = customKey;
} #endregion 其他
}
}
RedisHelper
4.使用
[HttpPost]
public JsonResult SetV()
{
bool result = new RedisCommon.RedisHelper().StringSet("name", "jay.star");
return Json("result:" + result, JsonRequestBehavior.AllowGet);
} [HttpGet]
public JsonResult GetV()
{
string name = new RedisCommon.RedisHelper().StringGet("name");
return Json("name:" + name, JsonRequestBehavior.AllowGet);
}
Redis—.Net中的使用的更多相关文章
- PHP redis Api 中文文档
phpredis是php的一个扩展,效率是相当高有链表排序功能,对创建内存级的模块业务关系 很有用;以下是redis官方提供的命令使用技巧: 下载地址如下: https://github.com/ow ...
- Redis配置文件中关于bind参数
在配置文件redis.conf中,默认的bind 接口是127.0.0.1,也就是本地回环地址.这样的话,访问redis服务只能通过本机的客户端连接,而无法通过远程连接,这样可以避免将redis服务暴 ...
- linux下安装redis及其中遇到的问题的解决方法
1.将下载好的压缩包放到/usr/local目录下# tar xzf redis-3.0.2.tar.gz # cd redis-3.0.2 # make 提示错误 make: cc: Command ...
- Redis used_cpu_sys used_cpu_user meaning (redis info中cpu信息的含义)
Redis 中 used_cpu_sys 和 used_cpu_user含义. 在Redis的info命令输出结果中有如下四个指标,redis官网给出了下面一段解释,但是还是不明白什么意思. used ...
- 具体解释Redis源代码中的部分高速排序算法(pqsort.c)
看标题.你可能会疑惑:咦?你这家伙.怎么不解说完整的快排,仅仅讲一部分快排---.- 哎,冤枉. "部分快排"是算法的名字.实际上本文相当具体呢.本文差点儿与普通快排无异.看懂了本 ...
- Redis配置文件中bind参数
前言 我们都知道,redis 的配置文件中,默认绑定接口是 127.0.0.1,也就是本地回环接口,所以是无法从外网连接 redis 服务的.如果想要让外网也能连接使用服务器上的 redis 服务,可 ...
- 获取redis实例中最大的top-N key
需求:获取redis实例中最大的top-N key 说明:由于redis 4.x才引入了memory usage keyname的语法.3.x不支持! db_ip=5.5.5.101 db_port= ...
- redis配置文件中常用配置详解
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/suprezheng/article/de ...
- springboot中如何向redis缓存中存入数据
package com.hope;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jack ...
- linux安装和配置 mysql、redis 过程中遇到的问题记录
linux下部署mysql和redis网上的教程很多,这里记录一下我部署.配置的过程中遇到的一些问题和解决办法. mysql ①安装完成后启动的时候报错 Starting MySQL.The serv ...
随机推荐
- Docs-.NET-C#-指南-语言参考-关键字-值类型:enum
ylbtech-Docs-.NET-C#-指南-语言参考-关键字-值类型:enum 1.返回顶部 1. enum(C# 参考) 2015/07/20 enum 关键字用于声明枚举,一种包含一组被称为枚 ...
- typescript类 继承 修饰符
//1.ts中类的定义 /* es5: function Person(name){ this.name=name; this.run=function(){ console.log(this.nam ...
- 从0开始学爬虫4之requests基础知识
从0开始学爬虫4之requests基础知识 安装requestspip install requests get请求:可以用浏览器直接访问请求可以携带参数,但是又长度限制请求参数直接放在URL后面 P ...
- Spark累加器(Accumulator)
一.累加器简介 在Spark中如果想在Task计算的时候统计某些事件的数量,使用filter/reduce也可以,但是使用累加器是一种更方便的方式,累加器一个比较经典的应用场景是用来在Spark St ...
- gitlab 配置到jenkins
直接把公匙配到了gitlab,然后填入jenkins https://blog.csdn.net/zhufengyan521521/article/details/81219193 配置全局凭据 h ...
- Python核心编程(第二版)PDF
Python核心编程(第二版) 目录 第1部分 Python核心第1章 欢迎来到Python世界1.1 什么是Python1.2 起源1.3 特点1.3.1 高级1.3.2 面向对象1.3.3 可升级 ...
- Django 引用{% url "name"%} 避免链接硬编码
前提条件:为每个url指定name且name值要唯一.比如: 项目中的url.py文件: urlpatterns = patterns('', url(r'^$',TemplateView.as_vi ...
- C语言中结构体的构造函数
示例代码: #include <iostream> using namespace std; struct Node { int x, y, z; Node(int _x, int _y, ...
- HDU3853 LOOPS 期望DP基础题
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3853 题目大意(只是大意,名字什么的可能和原题描述不一样~): 爱丽丝与华容道 题目描述 爱丽丝是一个 ...
- .Net Core 程序报错 在上一个操作完成之前,在此上下文上启动了第二个操作。
错误一: 程序完整报错: A second operation started on this context before a previous operation completed. This ...