zoukankan      html  css  js  c++  java
  • C# 简单操作缓存数据库Redis

    一、安装

    Nuget包管理器添加StackExchange.Redis的引用

    二、写入

    /// <summary>
    /// 向Redis写入
    /// </summary>
    /// <param name="key">键值</param>
    /// <param name="value"></param>
    /// <param name="date">过期日期</param>
    public static void SetString(string key,string value,DateTime? date = null)
    {
        //ConnectionMultiplexer.Connect("Localhost:6379,password=123456"))
        using (var redis = ConnectionMultiplexer.Connect("Localhost"))
        {
            //写入
            var db = redis.GetDatabase();
            db.StringSet("key", "123456");
            //设置过期日期
            if (date != null)
            {
                DateTime time = DateTime.Now.AddSeconds(20);
                db.KeyExpire("key", time);
            }
            var result = db.StringGet("key");
        }
    }

    三、读取

    /// <summary>
    /// 读取redis的内容
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetString(string key)
    {
        using (var redis = ConnectionMultiplexer.Connect("Localhost"))
        {
            //读取
            var db = redis.GetDatabase();
            var result = db.StringGet(key);
            return result;
        }
    }

    四、Redis封装类

    using ServiceStack.Redis;
    using Newtonsoft.Json;
      1     /// <summary>
      2     /// Redis 操作类
      3     /// </summary>
      4     public class RedisHelper
      5     {
      6         /// <summary>
      7         /// 连接字符串
      8         /// </summary>
      9         private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString;
     10         /// <summary>
     11         /// 12         /// </summary>
     13         private readonly object _lock = new object();
     14         /// <summary>
     15         /// 连接对象
     16         /// </summary>
     17         private volatile IConnectionMultiplexer _connection;
     18         /// <summary>
     19         /// 数据库
     20         /// </summary>
     21         private IDatabase _db;
     22         public RedisHelper()
     23         {
     24             _connection = ConnectionMultiplexer.Connect(ConnectionString);
     25             _db = GetDatabase();
     26         }
     27         /// <summary>
     28         /// 获取连接
     29         /// </summary>
     30         /// <returns></returns>
     31         protected IConnectionMultiplexer GetConnection()
     32         {
     33             if (_connection != null && _connection.IsConnected)
     34             {
     35                 return _connection;
     36             }
     37             lock (_lock)
     38             {
     39                 if (_connection != null && _connection.IsConnected)
     40                 {
     41                     return _connection;
     42                 }
     43 
     44                 if (_connection != null)
     45                 {
     46                     _connection.Dispose();
     47                 }
     48                 _connection = ConnectionMultiplexer.Connect(ConnectionString);
     49             }
     50 
     51             return _connection;
     52         }
     53         /// <summary>
     54         /// 获取数据库
     55         /// </summary>
     56         /// <param name="db"></param>
     57         /// <returns></returns>
     58         public IDatabase GetDatabase(int? db = null)
     59         {
     60             return GetConnection().GetDatabase(db ?? -1);
     61         }
     62         /// <summary>
     63         /// 设置
     64         /// </summary>
     65         /// <param name="key"></param>
     66         /// <param name="data"></param>
     67         /// <param name="cacheTime">时间</param>
     68         public virtual void Set(string key, object data, int cacheTime)
     69         {
     70             if (data == null)
     71             {
     72                 return;
     73             }
     74             var entryBytes = Serialize(data);
     75             var expiresIn = TimeSpan.FromMinutes(cacheTime);
     76 
     77             _db.StringSet(key, entryBytes, expiresIn);
     78         }
     79         /// <summary>
     80         /// 根据键获取值
     81         /// </summary>
     82         /// <typeparam name="T"></typeparam>
     83         /// <param name="key"></param>
     84         /// <returns></returns>
     85         public virtual T Get<T>(string key)
     86         {
     87 
     88             var rValue = _db.StringGet(key);
     89             if (!rValue.HasValue)
     90             {
     91                 return default(T);
     92             }
     93 
     94             var result = Deserialize<T>(rValue);
     95 
     96             return result;
     97         }
     98         /// <summary>
     99         /// 反序列化
    100         /// </summary>
    101         /// <typeparam name="T"></typeparam>
    102         /// <param name="serializedObject"></param>
    103         /// <returns></returns>
    104         protected virtual T Deserialize<T>(byte[] serializedObject)
    105         {
    106             if (serializedObject == null)
    107             {
    108                 return default(T);
    109             }
    110             var json = Encoding.UTF8.GetString(serializedObject);
    111             return JsonConvert.DeserializeObject<T>(json);
    112         }
    113         /// <summary>
    114         /// 判断是否已经设置
    115         /// </summary>
    116         /// <param name="key"></param>
    117         /// <returns></returns>
    118         public virtual bool IsSet(string key)
    119         {
    120             return _db.KeyExists(key);
    121         }
    122         /// <summary>
    123         /// 序列化
    124         /// </summary>
    125         /// <param name="data"></param>
    126         /// <returns>byte[]</returns>
    127         private byte[] Serialize(object data)
    128         {
    129             var json = JsonConvert.SerializeObject(data);
    130             return Encoding.UTF8.GetBytes(json);
    131         }
    132     }
    View Code

    五、查看Redis数据

    可以通过  Redis Desktop Manager 数据库管理工具查看。

     *****************************
     *** Keep learning and growing. ***
     *****************************
  • 相关阅读:
    Windows 和 Linux下使用socket下载网页页面内容(可设置接收/发送超时)的代码(用socket解释http,不错)
    HTTP协议 HttpWebRequest和 Socket的一点总结
    ASP.NET MVC基础学习
    利用HttpWebRequest和HttpWebResponse获取Cookie并实现模拟登录
    C#中Hashtable容器的了解与使用
    lib 和 dll 的区别、生成以及使用详解
    将SQL获取的信息传递到Email中
    关于ref与out的区别
    C#中指针使用总结
    一个打包文件导入器
  • 原文地址:https://www.cnblogs.com/gangle/p/9297708.html
Copyright © 2011-2022 走看看