• 【11】Redis .net 实例 StackExchange.Redis框架


    1.创建测试项目并下载nuget包:StackExchange.Redis

    PM> Install-Package StackExchange.Redis


     

    2.创建 RedisHelper类

    public class RedisHelper
    {
        private static string _conn = "127.0.0.1:6379";
    
        #region string类型
        /// <summary>
        /// 根据Key获取值
        /// </summary>
        /// <param name="key">键值</param>
        /// <returns>System.String.</returns>
        public static string StringGet(string key)
        {
            try
            {
                using (var client = ConnectionMultiplexer.Connect(_conn))
                {
                    return client.GetDatabase().StringGet(key);
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    
        /// <summary>
        /// 批量获取值
        /// </summary>
        public static string[] StringGetMany(string[] keyStrs)
        {
            var count = keyStrs.Length;
            var keys = new RedisKey[count];
            var addrs = new string[count];
    
            for (var i = 0; i < count; i++)
            {
                keys[i] = keyStrs[i];
            }
            try
            {
                using (var client = ConnectionMultiplexer.Connect(_conn))
                {
                    var values = client.GetDatabase().StringGet(keys);
                    for (var i = 0; i < values.Length; i++)
                    {
                        addrs[i] = values[i];
                    }
                    return addrs;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    
    
        /// <summary>
        /// 单条存值
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">The value.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool StringSet(string key, string value)
        {
    
            using (var client = ConnectionMultiplexer.Connect(_conn))
            {
                return client.GetDatabase().StringSet(key, value);
            }
        }
    
    
        /// <summary>
        /// 批量存值
        /// </summary>
        /// <param name="keysStr">key</param>
        /// <param name="valuesStr">The value.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool StringSetMany(string[] keysStr, string[] valuesStr)
        {
            var count = keysStr.Length;
            var keyValuePair = new KeyValuePair<RedisKey, RedisValue>[count];
            for (int i = 0; i < count; i++)
            {
                keyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(keysStr[i], valuesStr[i]);
            }
            using (var client = ConnectionMultiplexer.Connect(_conn))
            {
                return client.GetDatabase().StringSet(keyValuePair);
            }
        }
    
        #endregion
    
        #region 泛型
        /// <summary>
        /// 存值并设置过期时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">key</param>
        /// <param name="t">实体</param>
        /// <param name="ts">过期时间间隔</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool Set<T>(string key, T t, TimeSpan ts)
        {
            var str = JsonConvert.SerializeObject(t);
            using (var client = ConnectionMultiplexer.Connect(_conn))
            {
                return client.GetDatabase().StringSet(key, str, ts);
            }
        }
    
        /// <summary>
        /// 
        /// 根据Key获取值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <returns>T.</returns>
        public static T Get<T>(string key) where T : class
        {
            using (var client = ConnectionMultiplexer.Connect(_conn))
            {
                var strValue = client.GetDatabase().StringGet(key);
                return string.IsNullOrEmpty(strValue) ? null : JsonConvert.DeserializeObject<T>(strValue);
            }
        }
        #endregion
    }

    3.主程序调用

        class Program
        {
            static void Main(string[] args)
            {
                string key = "test", value = "http://www.sina.com";
                bool isRight = RedisHelper.StringSet(key, value);
                if(isRight)
                    Console.WriteLine("保存Redis:key.{0} value.{1}成功", key, value);
                string result = RedisHelper.StringGet(key);
                Console.WriteLine("Redis:key.{0} value.{1}", key, result);
                var model = new TestModel() { Id = 100, Name = "RedisValue" };
                isRight = RedisHelper.Set<TestModel>("model", model, new TimeSpan(0, 10, 0));
                var modelResult = RedisHelper.Get<TestModel>("model");
                if(modelResult != null)
                    Console.WriteLine("RedisModel:Id.{0} Name.{1}", modelResult.Id, modelResult.Name);
                Console.ReadLine();
            }
        }
    
        [Serializable]
        public class TestModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

    4.运行结果

    Windows环境安装参考上一篇

  • 相关阅读:
    书面采访时表示,小东西(数据库知识)
    UBuntu经常使用的操作(网络资源)
    hdu 5030 Rabbit&#39;s String(后缀数组&amp;二分法)
    Chapter 2 User Authentication, Authorization, and Security(4):限制SA帐户管理权限
    编程算法
    iOS:WebKit内核框架的应用与解析
    协议森林03 IP接力赛 (IP, ARP, RIP和BGP协议)
    以太网,IP,TCP,UDP数据包分析
    tcp 面向连接
    TCP传输层协议的流程
  • 原文地址:https://www.cnblogs.com/pengdylan/p/6729264.html
Copyright © 2020-2023  润新知