使用NuGet添加依赖包:Microsoft.Extensions.Caching.StackExchangeRedis
点击安装,我本地已经安装好了,所以只需要更新即可。
2.Redis注册在Startup文件的ConfigureServices方法中添加对Redis的注册
services.AddStackExchangeRedisCache(redis =>
{
redis.Configuration = CommonBLL.Config["DBString:RedisConn"];//配置文件配置
redis.InstanceName = "Test";//自定义
});
注意:在向Redis中存储键值对时的键为“InstanceName+自己定义的键”,因此可以通过设置不同的InstanceName来为不同的Application在Redis中做数据隔离,这就是InstanceName的作用
3.添加RedisHelper在程序中添加RedisHelper.cs类,下面给出两种方式
(1)方式一,该方式不包含对byte的 *** 作using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test.Models
{
public class RedisHelper
{
///
/// redis连接字符串
///
private static readonly string RedisConnString = CommonBLL.Config["DBString:RedisConn"];
//相当于上面设置的InstanceName
private static readonly string RedisKey = CommonBLL.Config["DBString:RedisKey"];
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private int DbNum { get; }
#region ConnectionMultiplexer实例
///
/// 单例获取
///
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = ConnectionMultiplexer.Connect(RedisConnString);
}
}
}
return _instance;
}
}
public RedisHelper(int dbnum = 1)
{
DbNum = dbnum;
}
#endregion
#region 扩展方法
private T Do(Func func)
{
var database = Instance.GetDatabase(DbNum);
return func(database);
}
private string ConvertJson(T value)
{
return JsonConvert.SerializeObject(value);
}
private T ConvertObj(RedisValue value)
{
return JsonConvert.DeserializeObject(value);
}
private List ConvertList(RedisValue[] value)
{
List result = new List();
foreach (var item in value)
{
result.Add(ConvertObj(item));
}
return result;
}
private RedisKey[] ConvertRedisKeys(List rediskey)
{
return rediskey.Select(key => (RedisKey)key).ToArray();
}
#endregion
#region String
///
/// 获取单个key的值
///
/// Redis Key
///
public string StringGet(string key)
{
key = RedisKey + key;
return Do(db => db.StringGet(key));
}
public string StringGet(string key, string CustomKey)
{
key = RedisKey + key;
return Do(db => db.StringGet(CustomKey + key));
}
///
/// 自定义key前缀
///
///
///
///
public string StringGet(string key, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db => db.StringGet(key));
}
///
/// 新增String键值
///
///
///
///
public bool StringSet(string key, string value)
{
key = RedisKey + key;
return Do(db => db.StringSet(key, value));
}
///
/// String键值自增
///
///
///
public bool IncrKey(string key)
{
key = RedisKey + key;
return Do(db => (db.StringIncrement(key) > 0) ? true : false);
}
#endregion
#region List
///
/// 获取列表
///
///
///
///
public List ListRange(string key)
{
key = RedisKey + key;
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvertList(values);
});
}
///
/// 左侧插入数据
///
///
///
///
public void ListLeftPush(string key, T value)
{
key = RedisKey + key;
Do(db => db.ListLeftPush(key, ConvertJson(value)));
}
///
/// 右侧插入数据
///
///
///
///
public void ListRightPush(string key, T value)
{
key = RedisKey + key;
Do(db => db.ListRightPush(key, ConvertJson(value)));
}
///
/// 对List中指定位置,重新赋值
///
///
///
///
///
public void ListLSet(string key, int index, T value)
{
key = RedisKey + key;
Do(db =>
{
db.ListSetByIndex(key, index, ConvertJson(value));
return true;
});
}
#endregion
#region Hash
///
/// 判断某个数据是否已经被缓存
///
///
///
///
public bool HashExists(string key, string dataKey)
{
key = RedisKey + key;
return Do(db => db.HashExists(key, dataKey));
}
///
/// 单个值存储数据到hash表
///
///
///
///
///
///
public bool HashSet(string key, string dataKey, T t)
{
key = RedisKey + key;
return Do(db =>
{
string str = t.ToString();
return db.HashSet(key, dataKey, str);
});
}
///
/// 单个值存储数据到hash表
///
///
///
///
/// 是否需要加上前缀:1是 0否
///
///
public bool HashSet(string key, string dataKey, T t, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
string str = t.ToString();
return db.HashSet(key, dataKey, str);
});
}
///
/// 单个值自增
///
///
///
///
///
public bool HashSetIncr(string key, string dataKey, int num)
{
key = RedisKey + key;
return Do(db =>
{
return db.HashIncrement(key, dataKey, num) > 0;
});
}
///
/// 单个值自增
///
///
///
///
///
public bool HashSetIncr(string key, string dataKey, int num, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
return db.HashIncrement(key, dataKey, num) > 0;
});
}
///
/// 多值(field)存储Hash
///
///
///
public void HashMSet(string key, HashEntry[] hashstr)
{
key = RedisKey + key;
var db = Instance.GetDatabase(DbNum);
db.HashSet(key, hashstr);
}
///
/// 获取hash所有键值对
///
///
/// 是否需要加上前缀:1是 0否
///
public HashEntry[] HashGetAll(string key, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
return db.HashGetAll(key);
});
}
public RedisValue[] HashGetAll(string key, RedisValue[] datafiled)
{
key = RedisKey + key;
return Do(db =>
{
return db.HashGet(key, datafiled);
});
}
///
/// 获取hash单个键值对
///
///
///
///
///
public string HashGet(string key, string dataKey)
{
key = RedisKey + key;
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return db.HashGet(key, dataKey).ToString();
});
}
///
/// 获取hash单个键值对
///
///
///
/// 是否加前缀:1是 0否
///
public string HashGet(string key, string dataKey, int isAdd)
{
key = isAdd == 1 ? RedisKey + key : key;
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return db.HashGet(key, dataKey).ToString();
});
}
///
/// 对Hash进行排序
///
///
///
///
public RedisValue[] HashSort(string key, string sortfiled, int sortOrder, RedisValue[] getfiled)
{
key = RedisKey + key;
return Do(db =>
{
return db.Sort(key, 0, -1, sortOrder == 1 ? Order.Ascending : Order.Descending, SortType.Numeric, sortfiled, getfiled);
});
}
#endregion
#region key
///
/// 设置key值过期时间
///
///
///
///
public bool KeyExpire(string key, TimeSpan expiry)
{
key = RedisKey + key;
return Do(db => db.KeyExpire(key, expiry));
}
///
/// key是否存在
///
///
///
public bool KeyExists(string key)
{
key = RedisKey + key;
return Do(db => db.KeyExists(key));
}
///
/// 模糊查询key名称,获取key集合(!!!注意,使用值时,不要再加前缀)
///
/// 关键字
///
public List GetLikeKey(string pattern)
{
pattern = RedisKey + pattern + "*";
return Do(db =>
{
var result = db.ScriptEvaluate(LuaScript.Prepare(" local res= redis.call('KEYS',@keypattern) return res"), new { @keypattern = pattern });
List list = new List((string[])result);
return list;
});
}
///
/// 删除单个key
///
///
///
public bool KeyDelete(string key)
{
key = RedisKey + key;
return Do(db => db.KeyDelete(key));
}
///
/// 根据关键字,模糊查询key集合,并删除
///
/// 关键字
///
public long KeysDelete(string pattern)
{
return Do(db =>
{
var _server = _instance.GetServer(_instance.GetEndPoints()[DbNum]);
var keys = _server.Keys(db.Database, pattern + "*");
return db.KeyDelete(keys.ToArray());
});
}
///
/// 删除key集合
///
///
///
public long KeysDelete(List key)
{
RedisKey[] value = ConvertRedisKeys(key);
return Do(db => db.KeyDelete(value));
}
#endregion
}
}
(2)方式二,该方式不包含对List和Hash的 *** 作,增加对byte的 *** 作
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.StackExchangeRedis;
using System.Threading;
using System.Threading.Tasks;
namespace Test.Models
{
public class RedisHelperSelf
{
public RedisCache redisCache;
public RedisCacheOptions redisCacheOptions;
public RedisHelperSelf()
{
redisCacheOptions=new RedisCacheOptions();
redisCacheOptions.Configuration= CommonBLL.Config["DBString:RedisConn"];
redisCacheOptions.InstanceName = "Test";
redisCache=new RedisCache(redisCacheOptions);
}
//注意:在向Redis中存储键值对时的键为“InstanceName+自己定义的键”,因此可以通过设置不同的InstanceName来为不同的Application在Redis中做数据隔离,这就是InstanceName的作用
#region byte[]
///
/// 获取单个key的值
///
///
/// byte[]
public byte[] Get(string key)
{
return redisCache.Get(key);
}
///
/// 获取单个key的值
///
///
/// 根据cancellationToken属性,控制结束线程
/// Task
public Task GetAsync(string key, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.GetAsync(key, cancellationToken);
}
///
/// 设置缓存
///
///
///
public void Set(string key, byte[] value)
{
redisCache.Set(key, value);
}
///
/// 设置缓存以及过期时间
///
///
///
/// 设置Redis缓存的过期策略,
/// 可以用其设置缓存的绝对过期时间(AbsoluteExpiration或AbsoluteExpirationRelativeToNow),
/// 例如: new DistributedCacheEntryOptions { AbsoluteExpiration=new System.DateTimeOffset()}
/// new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow=new System.TimeSpan(0, 500000, 0)}
/// 也可以设置缓存的滑动过期时间(SlidingExpiration)
/// 例如:new DistributedCacheEntryOptions { SlidingExpiration=new System.TimeSpan (0,500000,0) }
///
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
redisCache.Set(key, value, options);
}
///
/// 设置缓存以及过期时间
///
///
///
/// 同上
///
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
{
return redisCache.SetAsync(key, value, options);
}
///
/// 设置缓存以及过期时间
///
///
///
/// 同上
/// 根据cancellationToken属性,控制结束线程
///
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options,CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.SetAsync(key, value, options,cancellationToken);
}
#endregion
#region String
///
/// 获取单个key的值
///
///
/// string
public string GetString(string key)
{
return redisCache.GetString(key);
}
///
/// 获取单个key的值
///
///
/// Task
public Task GetStringAsync(string key)
{
return redisCache.GetStringAsync(key);
}
///
/// 获取单个key的值
///
///
/// 根据cancellationToken属性,控制结束线程
/// Task
public Task GetStringAsync(string key, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.GetStringAsync(key, cancellationToken);
}
///
/// 设置缓存
///
///
///
public void SetString(string key,string value)
{
redisCache.SetString(key, value);
}
///
/// 设置缓存以及过期时间
///
///
///
/// 设置Redis缓存的过期策略,
/// 可以用其设置缓存的绝对过期时间(AbsoluteExpiration或AbsoluteExpirationRelativeToNow),
/// 例如: new DistributedCacheEntryOptions { AbsoluteExpiration=new System.DateTimeOffset()}
/// new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow=new System.TimeSpan(0, 500000, 0)}
/// 也可以设置缓存的滑动过期时间(SlidingExpiration)
/// 例如:new DistributedCacheEntryOptions { SlidingExpiration=new System.TimeSpan (0,500000,0) }
///
public void SetString(string key, string value, DistributedCacheEntryOptions options)
{
redisCache.SetString(key, value, options);
}
///
/// 设置缓存以及过期时间
///
///
///
///
///
public Task SetStringAsync(string key,string value, DistributedCacheEntryOptions options)
{
return redisCache.SetStringAsync(key, value, options);
}
///
/// 设置缓存以及过期时间
///
///
///
///
/// 根据cancellationToken属性,控制结束线程
///
public Task SetStringsync(string key, string value, DistributedCacheEntryOptions options, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.SetStringAsync(key, value, options, cancellationToken);
}
#endregion
#region Refresh
///
/// 从Redis中刷新键值
///
/// 缓存键
public void Refresh(string key)
{
redisCache.Refresh(key);
}
///
/// Redis中刷新键值
///
///
///
///
public Task RefreshAsync(string key)
{
return redisCache.RefreshAsync(key);
}
///
/// Redis中刷新键值
///
///
/// 根据cancellationToken属性,控制结束线程
///
public Task RefreshAsync(string key, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.RefreshAsync(key, cancellationToken);
}
#endregion
#region Remove
///
/// 从Redis中删除键值
///
///
public void Remove(string key)
{
redisCache.Remove(key);
}
///
/// 从Redis中删除键值
///
///
///
public Task RemoveAsync(string key)
{
return redisCache.RemoveAsync(key);
}
///
/// 从Redis中删除键值
///
///
/// 根据cancellationToken属性,控制结束线程
///
public Task RemoveAsync(string key,CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
//自定义逻辑
}
return redisCache.RemoveAsync(key,cancellationToken);
}
#endregion
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)