.NET平台下Redis使用(四)【StackExchangeRedisHelper助手类】

本文介绍了一个使用 C# 进行 Redis 数据缓存的示例程序,通过序列化对象并将其存储到 Redis 中,实现了数据的高效读取与存储。该示例展示了如何创建对象列表、设置 Redis 连接、存储及获取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

敢为自己目标行动的人,整个世界都会为你让路


Program.cs主程序:

  class Program
    {
        static void Main(string[] args)
        {
            List<User> userList =new List<User>() {
                new User { UserName = "chengjun", PassWord = "qwerty" }, 
                new User { UserName = "chengjun1", PassWord = "qwerty" },
                new User { UserName = "chengjun2", PassWord = "qwerty" },
                new User { UserName = "chengjun3", PassWord = "qwerty" },
                new User { UserName = "chengjun5", PassWord = "qwerty" },
                new User { UserName = "chengjun6", PassWord = "qwerty" },
                new User { UserName = "chengjun7", PassWord = "qwerty" },
                new User { UserName = "chengjun8", PassWord = "qwerty" }
            };
            var stackExchangeHelper  = new StackExchangeHelper();
            stackExchangeHelper.Set("xxoo_cus", userList);
            var getUserListFromRedis = stackExchangeHelper.Get<List<User>>("xxoo_cus");

            Console.WriteLine("List元素数量:"+getUserListFromRedis.Count);
            Console.ReadKey();
        }
    }


    [Serializable]
    public class User
    {
        public string UserName { get; set; }
        public string PassWord { get; set; }
    }

PubConstant.cs代码:

  public class PubConstant
    {
        public static string RedisIp
        {
            get
            {
                string _redisIp = ConfigurationManager.AppSettings["RedisIp"];
                return _redisIp;
            }
        }
        public static string RedisPort
        {
            get
            {
                string _redisPort = ConfigurationManager.AppSettings["RedisPort"];
                return _redisPort;
            }
        }
        public static string RedisPass
        {
            get
            {
                string _redisPass=ConfigurationManager.AppSettings["RedisPass"];
                return _redisPass;
            }
        }
    }

App.config代码:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <!--RedisIP-->
    <add key="RedisIp" value="127.0.0.1" />
    <!--RedisPort-->
    <add key="RedisPort" value="6379" />
    <!--RedisPass-->
    <add key="RedisPass" value="123456" />
  </appSettings>
</configuration>

StackExchangeConn.cs代码:

  public class StackExchangeConn
    {
        private static ConnectionMultiplexer _connection;
        private static readonly object SyncObject = new object();
        public static ConnectionMultiplexer GetFactionConn
        {
            get
            {
                if (_connection == null || !_connection.IsConnected)
                {
                    lock (SyncObject)
                    {
                        var configurationOptions = new ConfigurationOptions()
                        {
                            Password = PubConstant.RedisPass,
                            EndPoints = { { PubConstant.RedisIp, Convert.ToInt32(PubConstant.RedisPort) } }
                        };
                        //"192.168.100.37,password=123456";
                        _connection = ConnectionMultiplexer.Connect(configurationOptions);
                    }
                }
                return _connection;
            }
        }
    }

StackExchangeHelper.cs助手类

 public class StackExchangeHelper
    {
        private  static IDatabase cache;
        public StackExchangeHelper()
        {
            cache = StackExchangeConn.GetFactionConn.GetDatabase();
        }
        /// <summary>
        /// 添加string类型数据到redis
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool StringSet(string key, string value)
        {
            return cache.StringSet(key, value);
        }
        /// <summary>
        /// 从redis中获取string类型数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string StringGet(string key)
        {
            return cache.StringGet(key);
        }
        /// <summary>
        /// 从redis中获取Int类型数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int IntGet(string key)
        {
            try
            {
                return Convert.ToInt32(StringGet(key));
            }
            catch (Exception)
            {
                return (-9999);
            }
        }
        /// <summary>
        /// 根据key获取指定类型数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            return Deserialize<T>(cache.StringGet(key));
        }
        /// <summary>
        /// 根据key获取object类型数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object Get(string key)
        {
            return Deserialize<object>(cache.StringGet(key));
        }
        /// <summary>
        /// 将数据添加到redis中
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Set(string key, object value)
        {
            cache.StringSet(key, Serialize(value));
        }
        static byte[] Serialize(object o)
        {
            if (o == null)
            {
                return null;
            }

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                binaryFormatter.Serialize(memoryStream, o);
                byte[] objectDataAsStream = memoryStream.ToArray();
                return objectDataAsStream;
            }
        }

        static T Deserialize<T>(byte[] stream)
        {
            if (stream == null)
            {
                return default(T);
            }

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using (MemoryStream memoryStream = new MemoryStream(stream))
            {
                T result = (T)binaryFormatter.Deserialize(memoryStream);
                return result;
            }
        }
    }

运行结果:

这里写图片描述


这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值