C# 实现Redis客户端;实时数据缓存用法

1 篇文章 0 订阅

一、Redis服务端

下载Redis解压,设置配置文件参数,端口、密码等,运行,具体参见:

https://www.runoob.com/redis/redis-install.html

二、Redis客户端

NuGet添加StackExchange.Redis.StrongName库

public class RedisClient
    {
        private string _redisServerIp = string.Empty;
        private int _redisServerPort = 0;
        private string _pwd = string.Empty;

        private ConnectionMultiplexer _redisConnection = null;
        private object _connLock = new object();
        /// <summary>
        /// 初始化函数
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="pwd"></param>
        public RedisClient(string ip, int port, string pwd)
        {
            _redisServerIp = ip;
            _redisServerPort = port;
            _pwd = pwd;
        }

        /// <summary>
        /// 是否已链接
        /// </summary>
        public bool IsConnected
        {
            get
            {
                try
                {
                    lock (_connLock)
                    {
                        if (_redisConnection == null)
                        {
                            return false;
                        }
                        else
                        {
                            return _redisConnection.IsConnected;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

        }

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="IsKeepAlive">是否保存链接</param>
        /// <returns></returns>
        public bool Connect(bool IsKeepAlive = true)
        {
            try
            {

                ConfigurationOptions co = new ConfigurationOptions();
                co.Password = _pwd;
                co.EndPoints.Add(_redisServerIp, _redisServerPort);
                co.ConnectRetry = 3;
                co.AbortOnConnectFail = true;
                if (IsKeepAlive)
                {
                    co.KeepAlive = 10;
                }

                lock (_connLock)
                {
                    if (_redisConnection == null)
                    {
                        _redisConnection = ConnectionMultiplexer.Connect(co);
                    }
                    else
                    {
                        if (!_redisConnection.IsConnected)
                        {
                            _redisConnection.Close();
                        }

                        _redisConnection = ConnectionMultiplexer.Connect(co);
                    }

                    return _redisConnection.IsConnected;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 断开链接
        /// </summary>
        /// <returns></returns>
        public bool DisConnect()
        {
            try
            {
                lock (_connLock)
                {
                    if (_redisConnection == null)
                    {
                        return true;
                    }
                    else
                    {
                        _redisConnection.Close();
                        _redisConnection = null;
                        return true;
                    }

                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 写入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="ExpiryTimeSecond"></param>
        /// <returns></returns>
        public bool SetObject<T>(string Key, T Value, int ExpiryTimeSecond = 300) where T : class
        {
            try
            {
                if (!IsConnected)
                {
                    if (!Connect())
                    {
                        return false;
                    }
                }

                if (string.IsNullOrEmpty(Key))
                {
                    return false;
                }
                string val = JsonConvert.SerializeObject(Value);
                if (string.IsNullOrEmpty(val))
                {
                    return false;
                }
                lock (_connLock)
                {
                    return _redisConnection.GetDatabase().StringSet(Key, val, new TimeSpan(0, 0, ExpiryTimeSecond));
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Key"></param>
        /// <returns></returns>
        public T GetObject<T>(string Key) where T : class
        {
            try
            {
                if (!IsConnected)
                {
                    if (!Connect())
                    {
                        return null;
                    }
                }

                if (string.IsNullOrEmpty(Key))
                {
                    return null;
                }

                string cont = string.Empty;
                lock (_connLock)
                {
                    cont = _redisConnection.GetDatabase().StringGet(Key);
                }

                if (string.IsNullOrEmpty(cont))
                {
                    return null;
                }

                return JsonConvert.DeserializeObject<T>(cont);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

    }

三、调用测试

        RedisClient _redisClient;
        private void button_Click(object sender, RoutedEventArgs e)
        {
            _redisClient = new RedisClient(textBox.Text, int.Parse(textBox1.Text), textBox2.Text);
            bool res = _redisClient.Connect();
            label3.Content = res + DateTime.Now.ToShortTimeString();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (_redisClient != null)
            {
                _redisClient.SetObject<String>(textBox3.Text, textBox4.Text);
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (_redisClient != null)
            {
                string temp = _redisClient.GetObject<String>(textBox5.Text);
                label8.Content = DateTime.Now.ToShortTimeString() + ": " + temp;
            }
        }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值