Net项目中使用Redis

https://github.com/tporadowski/redis/releases。下载redis

然后在vs中

<connectionStrings>
      <add name="AiXiuRedis" connectionString="127.0.0.1:6379" />
    <add name="AiShowDbContext" connectionString="data source=.;initial catalog=DBAiXiu;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>

 

 

1. 打开NuGet管理器搜索redis,安装:“StackExchange.Redis”

  

2. 配置 Web.config 文件

  <connectionStrings>
    <add name="connStr" connectionString="mongodb://127.0.0.1:27017/mydb01" />      <!-- 在有些版本里面如果不带上数据库名称会出错 -->
    <add name="redis" connectionString="127.0.0.1"/>          <!-- Redis -->
  </connectionStrings>

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
       /// <summary>
        /// 获取数据库
        /// </summary>
        /// <param name="dbnumber"></param>
        /// <returns></returns>
        public static IDatabase GetDatabase(int dbnumber)
        {
            ConnectionMultiplexer server = ConnectionMultiplexer.Connect(redisConn);
            return server.GetDatabase(dbnumber);
        }
    }

    /// <summary>
    /// Redis缓存扩展:保存、获取、删除(不过其实好像没有用到,引用的框架了好像已经带有这个方法了)
    /// </summary>
    public static class RedisExt
    {
        /// <summary>
        /// 保存一个对象(string类型)
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="experation"></param>
        /// <returns></returns>
        public static async Task<bool> SetAsync(this IDatabaseAsync cache, string key, object value,TimeSpan experation)
        {
            return await cache.StringSetAsync(key, JsonConvert.SerializeObject(value), experation);
        }

        /// <summary>
        /// 获取一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static async Task<T> GetTAsync<T>(this IDatabaseAsync cache,string key)
        {
            var value = await cache.StringGetAsync(key).ConfigureAwait(false);
            if(!value.IsNull)
            {
                return JsonConvert.DeserializeObject<T>(value);
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// 删除一个对象
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static async Task<bool> 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));

            //发送手机验证码
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private static string GetRandomString(int length)
        {
            return Guid.NewGuid().ToString("N").Substring((32 - length), length);
        }
复制代码

  这里只使用了保存,还有获取和删除,要注意key要对应。

posted @ 2021-12-16 12:54  裳裳者华  阅读(117)  评论(0编辑  收藏  举报