Net项目中使用Redis(12.22)
1. 打开NuGet管理器搜索redis,安装:“StackExchange.Redis”
2. 配置 Web.config 文件
3. 添加 Redis.cs 文件
复制代码
复制代码
public class Redis
{
private static readonly string redisConn = ConfigurationManager.ConnectionStrings["redis"].ToString();
#region 常用的数据库
public static IDatabase Top { get; } = GetDb(0);
public static IDatabase TopOauth { get; } = GetDb(1);
public static IDatabase TopService { get; } = GetDb(2);
#endregion
///
/// 获取数据库
///
///
///
public static IDatabase GetDatabase(int dbnumber)
{
ConnectionMultiplexer server = ConnectionMultiplexer.Connect(redisConn);
return server.GetDatabase(dbnumber);
}
}
///
/// Redis缓存扩展:保存、获取、删除(不过其实好像没有用到,引用的框架了好像已经带有这个方法了)
///
public static class RedisExt
{
///
/// 保存一个对象(string类型)
///
///
///
///
///
///
public static async Task SetAsync(this IDatabaseAsync cache, string key, object value,TimeSpan experation)
{
return await cache.StringSetAsync(key, JsonConvert.SerializeObject(value), experation);
}
///
/// 获取一个对象
///
///
///
///
///
public static async Task GetTAsync(this IDatabaseAsync cache,string key)
{
var value = await cache.StringGetAsync(key).ConfigureAwait(false);
if(!value.IsNull)
{
return JsonConvert.DeserializeObject(value);
}
else
{
return default(T);
}
}
///
/// 删除一个对象
///
///
///
///
public static async Task DelAsync(this IDatabaseAsync cache,string key)
{
return await cache.KeyDeleteAsync(key).ConfigureAwait(false);
}
}
复制代码
复制代码
4. Redis 的使用
复制代码
复制代码
public async Task GetCodeAsync(string mobile)
{
string id = ObjectId.GenerateNewId().ToString();
var text = GetRandomString(6); //验证码
//存储缓存(形式是这种形式,但实际应用不一定要这样用,要灵活运用key的形式)
await Redis.TopOauth.StringSetAsync($"SMSCODE:{mobile}", text.ToLower(), new TimeSpan(0, 5, 0));
//发送手机验证码
}
///
/// 生成随机字符串
///
///
///
private static string GetRandomString(int length)
{
return Guid.NewGuid().ToString("N").Substring((32 - length), length);
}