在C#中使用Redis

一、下载ServiceStack.Redis

  VS2015版本

二、将解压后的文件中下面四个dll引用到项目中

三、用C#对redis来进行简单的读取和写入操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Common.Extensions;
using ServiceStack.Redis;
using ServiceStack.Logging;
using System.Threading.Tasks;

namespace RedisDemo.Redis
{
    public class RedisConfigInfo
    {
        //唯一实例
        private static RedisConfigInfo uniqueInstance;

        //public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);

        //public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
        //定义一个标识确保线程同步

        private static readonly object locker = new object();

        private readonly string[] redisHosts = null;
        //链接池管理对象
        private PooledRedisClientManager _pool;
        //私有构造方法
        private RedisConfigInfo()
        {
            //创建连接池管理对象
            var redisHostStr = "127.0.0.1:6379";
            redisHosts = redisHostStr.Split(',');
            CreateRedisPoolManager(redisHostStr.Split(','), redisHostStr.Split(','));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="redisWriteHost"></param>
        /// <param name="redisReadHost"></param>
        private void CreateRedisPoolManager(string[] redisWriteHost, string[] redisReadHost)
        {
            _pool = new PooledRedisClientManager(redisWriteHost, redisReadHost, new RedisClientManagerConfig()
            {
                MaxWritePoolSize = redisHosts.Length * 5,
                MaxReadPoolSize = redisHosts.Length * 5,
                AutoStart = true
            });

        }

        //唯一全局访问点
        public static RedisConfigInfo GetRedisConfigInfo()
        {
            //双重锁定
            if (uniqueInstance == null)
            {
                lock (locker)
                {
                    if (uniqueInstance == null)
                    {
                        uniqueInstance = new RedisConfigInfo();
                    }
                }
            }
            return uniqueInstance;
        }

        public T _GetKey<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }
            T obj = default(T);
            try
            {
                if (_pool != null)
                {
                    using (var r = _pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            obj = r.Get<T>(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
            }
            return obj;
        }

        public bool _AddKey<T>(string key, T value)
        {
            if (value == null)
            {
                return false;
            }

            try
            {
                if (_pool != null)
                {
                    using (var r = _pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value);
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }
            return false;
        }


    }
}
RedisConfigInfo.cs

在webform中,可以进行一下简单的测试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RedisDemo.Redis;
using SinoFingerWeb.BLL;
using CngrainPrice.Model;

namespace WebFormRedisDemo
{
    public partial class Redis : System.Web.UI.Page
    {
        f_ComparedIndexBLL bll = new f_ComparedIndexBLL();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            RedisHelper rediss = RedisHelper.GetInstance();
            string key = TextBox1.Text.ToString();
            string value = TextBox2.Text.ToString();
          
            if (string.IsNullOrEmpty(key)||string.IsNullOrEmpty(value))
            {
                Response.Write("<script>confirm(\"请输入正确的keys和value!\");</script>");
                return;
            }


            if (!rediss.Add<string>(key,value,0))
            {
                Response.Write("<script>confirm(\"添加失败!\");</script>");
            }
            else
            {
                Response.Write("<script>confirm(\"添加成功!\");</script>");
                TextBox1.Text = "";
                TextBox2.Text = "";
            }

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            RedisConfigInfo redis = RedisConfigInfo.GetRedisConfigInfo();
            string key = TextBox3.Text.ToString();
            TextBox4.Text = redis._GetKey<string>(key);
        }




    }
}
RedisTest.aspx

 

转载于:https://www.cnblogs.com/zyc19910109/p/8351774.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值