引用包
dotnet add package CSRedisCore --version 3.6.8
应用模式
工厂模式
- 添加工具类:CSRedisHelper.cs
///
/// Redis帮助类
///
public class CSRedisHelper
{
static CSRedisClient redisManger = null;
static CSRedisClient GetClient()
{
return redisManger;
}
public CSRedisHelper(string connectionString)
{
redisManger = new CSRedisClient(connectionString); //Redis的连接字符串
}
///
/// 获取指定的键的集合
///
///
///
public List Keys(string pattern = null)
{
if (string.IsNullOrWhiteSpace(pattern))
pattern = "*";
return GetClient().Keys(pattern).ToList();
}
}
- 添加工厂类:RedisClientFactory.cs
///
/// Redis工厂类
///
public class RedisClientFactory
{
private static readonly ConcurrentDictionary CSRedisClients =
new ConcurrentDictionary();
public static CSRedisHelper GetClient(string connectionString)
{
return CSRedisClients.GetOrAdd(connectionString, new CSRedisHelper(connectionString));
}
}
- 测试调用
protected static readonly CSRedisHelper RedisService =
RedisClientFactory.GetClient("连接字符串");
public static void TestDeleteAll()
{
var watch = new Stopwatch();
watch.Start();
var keys = RedisService.Keys();
if (!keys.IsNullOrNotData())
{
RedisService.KeyDel(keys);
}
watch.Stop();
var ts = watch.Elapsed;
Console.WriteLine($"删除{keys.Count}花费了{ts.TotalSeconds}");
}
集成到构造器类
- 添加拓展工具类CacheExtension.cs
public static class CacheExtension
{
///
/// 使用缓存
///
/// 建造者
///
public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
{
hostBuilder.ConfigureServices((buidlerContext, services) =>
{
var CacheType = buidlerContext.Configuration["CacheType"].ToString();
switch (CacheType)
{
case "Memory": services.AddDistributedMemoryCache(); break;
case "Redis":
{
// => 初始化redis的两种使用方式
var csredis = new CSRedisClient(buidlerContext.Configuration["RedisConn"].ToString());
// 使用RedisHelper
services.AddSingleton(csredis);
RedisHelper.Initialization(csredis);
// 依赖注入使用自定义工具类
services.AddSingleton(new CSRedisCache(csredis));
}; break;
default: throw new Exception("缓存类型无效");
}
});
return hostBuilder;
}
}
- 添加接口:ICSRedisCache
///
/// CSRedis帮助类
///
public interface ICSRedisCache
{
///
/// 根据Key获取值
///
///
///
///
T StringGet(string key);
}
- 添加实现类:CSRedisCache
///
/// Redis帮助实现类
///
public class CSRedisCache : ICSRedisCache
{
private CSRedisClient csredis;
public CSRedisCache(CSRedisClient csredis)
{
this.csredis = csredis;
}
///
/// 获取指定key的值
///
///
///
///
public T StringGet(string key)
{
return csredis.Get(key);
}
}
- 在Program.cs中调用
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
})
// => 使用Redis
.UseCache();
- 接口测试
private readonly ICSRedisCache _iCSRedisCache;
///
/// 构造函数依赖注入
///
///
public TestRedisController(ICSRedisCache cSRedisCache)
{
_iCSRedisCache = cSRedisCache;
}
[HttpGet]
public ActionResult GetValueByKey(string key)
{
var value = _iCSRedisCache.StringGet(key);
return Ok(value);
}