zoukankan      html  css  js  c++  java
  • 在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
  • 相关阅读:
    leetCode 87.Scramble String (拼凑字符串) 解题思路和方法
    《代码阅读》读书笔记(一)
    用VMware 8安装Ubuntu 12.04具体过程(图解)
    模板方法
    POJ 2528 Mayor&#39;s posters 离散化+线段树
    <Linux> Xen虚拟机镜像的安装
    Android中的动画详解系列【2】——飞舞的蝴蝶
    jQuery:多个AJAX/JSON请求对应单个回调
    Android中的动画详解系列【1】——逐帧动画
    Android自定义组件系列【4】——自定义ViewGroup实现双侧滑动
  • 原文地址:https://www.cnblogs.com/zyc19910109/p/8351774.html
Copyright © 2011-2022 走看看