Redis连接

using System;
using System.Configuration;
using StackExchange.Redis;

namespace Redis
{
    public sealed class RedisDbContext
    {
        /// <summary>
        /// Redis连接器
        /// </summary>
        private static Lazy<ConnectionMultiplexer> _lazyConnection;

        /// <summary>
        /// Redis单例.
        /// </summary>
        /// <returns></returns>
        public static IDatabase Instance()
        {
            return Instance(null);
        }

        /// <summary>
        /// Redis单例.
        /// </summary>
        /// <param name="connectionString">Redis服务器连接地址.</param>
        /// <returns></returns>
        public static IDatabase Instance(string connectionString)
        {
            return Instance(connectionString, 0);
        }

        /// <summary>
        ///  Redis单例.
        /// </summary>
        /// <param name="connectionString">Redis服务器连接地址.</param>
        /// <param name="db">Redis服务器数据库索引(0-10).</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">Redis服务器单例过程失败</exception>
        public static IDatabase Instance(string connectionString, int db)
        {
            if (_lazyConnection == null)
            {
                lock (typeof(RedisDbContext))
                {
                    if (_lazyConnection == null)
                    {
                        if (string.IsNullOrWhiteSpace(connectionString))
                        {
                            InitRedis();
                        }
                        else
                        {
                            InitRedis(connectionString);
                        }
                    }
                }
            }

            if (_lazyConnection == null)
            {
                throw new Exception("Redis服务器连接失败");
            }

            return _lazyConnection.Value.GetDatabase(db);
        }

        /// <summary>
        /// 初始化Redis连接器.
        /// </summary>
        private static void InitRedis()
        {
            InitRedis(ConfigurationManager.AppSettings["RedisConnection"]);
        }

        /// <summary>
        /// 初始化Redis连接器.
        /// </summary>
        /// <param name="connectionString">Redis服务器连接地址.</param>
        /// <exception cref="System.ArgumentNullException">Redis服务器连接地址ConnectionString未配置</exception>
        private static void InitRedis(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("Redis服务器地址未配置");
            }

            _lazyConnection = new Lazy<ConnectionMultiplexer>(
                () => ConnectionMultiplexer.Connect(new ConfigurationOptions()
                {
                    AbortOnConnectFail = false,
                    EndPoints = { connectionString }
                }));
        }
    }
}

 

posted @ 2016-11-18 10:07  zslm___  阅读(728)  评论(1编辑  收藏  举报