首页 > 代码库 > 高性能网站架构设计之缓存篇(1)- Redis C#客户端

高性能网站架构设计之缓存篇(1)- Redis C#客户端

一、什么 Redis

REmote DIctionary Server,简称 Redis,是一个类似于Memcached的Key-Value存储系统。相比Memcached,它支持更丰富的数据结构,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型),并提供了数据持久化机制,在某些场景下,你完全可以把它当做非关系型数据库来使用。它是一个高性能的存储系统,能支持超过 100K+ 每秒的读写频率。同时还支持消息的发布/订阅,从而让你在构建高性能消息队列系统时多了另一种选择。

二、下载

点击这里下载。

我在这里下载的是redis-3.0.0-beta5版,redis从3.0开始支持集群。
三、安装

以下安装均为 OSX 操作系统上的步骤:

1、找到你刚刚下载的 redis-3.0.0-beta5.tar.gz文件,解压这个文件。

2、将解压后的文件夹拷贝到你很容易找到的目录下,并修改文件夹名为redis,因为版本号太长了。

2、打开终端,进入redis文件夹,命令如下:

Last login: Fri May 30 21:33:25 on ttys000

zhaoguihuadediannao:~ zhaogh$ cd applications/dev/redis

zhaoguihuadediannao:redis zhaogh$

3、在命令提示符出输入 make 命令,稍等片刻,便能完成安装。如果系统提示找不到 make 命令,请参考这篇文章。

装好了,是不是有点小激动。抽根烟,我们继续吧。

四、使用

1、启动服务,先进入 src 目录,然后执行 redis-server。

zhaoguihuadediannao:redis zhaogh$ cd src

zhaoguihuadediannao:src zhaogh$ ./redis-server

你将会看到:

2343:M 30 May 21:42:50.741 # Server started, Redis version 2.9.54

2343:M 30 May 21:42:50.741 * The server is now ready to accept connections on port 6379

我没看错吧,TMD我明明下载的3.0.0,怎么显示 Redis version 2.9.54 ? 好吧,这不是重点,我也懒得追究了。

6379 是 redis 默认端口,在后续的文章中你将知道如何修改这个默认端口。

2、客户端连接。

你会发现在执行了第四步之后,我们无法再执行其他命令了,怎么办?因为redis独占了此进程,后面告诉你们如果将它修改为后台运行。

我们暂且再打开一个终端吧。还是先进入 src 目录:

zhaoguihuadediannao:~ zhaogh$ cd applications/dev/redis/src

zhaoguihuadediannao:src zhaogh$

输入 ./redis-cli 命令:

zhaoguihuadediannao:src zhaogh$ ./redis-cli

127.0.0.1:6379>

已经连接上了,哈哈哈。

3、测试几个 redis 命令:

127.0.0.1:6379> set testkey001 testkey001

OK

127.0.0.1:6379> get testkey001

"testkey001"

127.0.0.1:6379> append testkey001 aaa

(integer) 13

127.0.0.1:6379> get testkey001

"testkey001aaa"

127.0.0.1:6379>
4、关闭连接,执行 quit 命令

127.0.0.1:6379> quit

zhaoguihuadediannao:src zhaogh$

5、关闭服务。

由于我们刚才已经退出了客户端,我们再次连接,并执行 shutdown 命令:

127.0.0.1:6379> shutdown

下面提供一个resdis帮助类

 

 /// <summary>  
    /// Redis公共辅助类库  
    /// </summary>  
    public class RedisHelper : IDisposable
    {
        public RedisClient Redis = new RedisClient("127.0.0.1", 6379);
        //缓存池  
        PooledRedisClientManager prcm = new PooledRedisClientManager();
        //默认缓存过期时间单位秒  
        public int secondsTimeOut = 30 * 60;

        /// <summary>  
        /// 缓冲池  
        /// </summary>  
        /// <param name="readWriteHosts"></param>  
        /// <param name="readOnlyHosts"></param>  
        /// <returns></returns>  
        public static PooledRedisClientManager CreateManager(
         string[] readWriteHosts, string[] readOnlyHosts)
        {
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts,
                new RedisClientManagerConfig
                {
                    MaxWritePoolSize = readWriteHosts.Length * 5,
                    MaxReadPoolSize = readOnlyHosts.Length * 5,
                    AutoStart = true,
                });// { RedisClientFactory = (IRedisClientFactory)RedisCacheClientFactory.Instance.CreateRedisClient("127.0.0.1", 6379) };            
        }


        /// <summary>  
        /// 构造函数  
        /// </summary>  
        /// <param name="openPooledRedis">是否开启缓冲池</param>  
        public RedisHelper(bool openPooledRedis = false)
        {
            if (openPooledRedis)
            {
                prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" });
                Redis = prcm.GetClient() as RedisClient;
            }
        }

 #region Key/Value存储  
        /// <summary>  
        /// 设置缓存  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="key">缓存建</param>  
        /// <param name="t">缓存值</param>  
        /// <param name="timeout">过期时间,单位秒,-1:不过期,0:默认过期时间</param>  
        /// <returns></returns>  
        public bool Set<T>(string key, T t, int timeout = 0)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }

            return Redis.Add<T>(key, t);
        }
        /// <summary>  
        /// 获取  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>  
        /// <returns></returns>  
        public T Get<T>(string key)
        {
            return Redis.Get<T>(key);
        }
        /// <summary>  
        /// 删除  
        /// </summary>  
        /// <param name="key"></param>  
        /// <returns></returns>  
        public bool Remove(string key)
        {
            return Redis.Remove(key);
        }

        public bool Add<T>(string key, T t, int timeout)
        {
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(key, secondsTimeOut);
            }
            return Redis.Add<T>(key, t);
        }
        #endregion

        #region 链表操作  
        /// <summary>  
        /// 根据IEnumerable数据添加链表  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="listId"></param>  
        /// <param name="values"></param>  
        /// <param name="timeout"></param>  
        public void AddList<T>(string listId, IEnumerable<T> values, int timeout = 0)
        {
            Redis.Expire(listId, 60);
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
            var redisList = iredisClient.Lists[listId];
            redisList.AddRange(values);
            iredisClient.Save();
        }

/// <summary>  
        /// 添加单个实体到链表中  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="listId"></param>  
        /// <param name="Item"></param>  
        /// <param name="timeout"></param>  
        public void AddEntityToList<T>(string listId, T Item, int timeout = 0)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            if (timeout >= 0)
            {
                if (timeout > 0)
                {
                    secondsTimeOut = timeout;
                }
                Redis.Expire(listId, secondsTimeOut);
            }
            var redisList = iredisClient.Lists[listId];
            redisList.Add(Item);
            iredisClient.Save();
        }
        /// <summary>  
        /// 获取链表  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="listId"></param>  
        /// <returns></returns>  
        public IEnumerable<T> GetList<T>(string listId)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            return iredisClient.Lists[listId];
        }
        /// <summary>  
        /// 在链表中删除单个实体  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="listId"></param>  
        /// <param name="t"></param>  
        public void RemoveEntityFromList<T>(string listId, T t)
        {
            IRedisTypedClient<T> iredisClient = Redis.As<T>();
            var redisList = iredisClient.Lists[listId];
            redisList.RemoveValue(t);
            iredisClient.Save();
        }
        /// <summary>  
        /// 根据lambada表达式删除符合条件的实体  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="listId"></param>  
        /// <param name="func"></param>  
        public void RemoveEntityFromList<T>(string listId, Func<T, bool> func)
        {
            using (IRedisTypedClient<T> iredisClient = Redis.As<T>())
            {
                var redisList = iredisClient.Lists[listId];
                T value = http://www.mamicode.com/redisList.Where(func).FirstOrDefault();
                redisList.RemoveValue(value);
                iredisClient.Save();
            }
        }
        #endregion

 

/// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (Redis != null)
            {
                Redis.Dispose();
                Redis = null;
            }
            GC.Collect();
        }

 

高性能网站架构设计之缓存篇(1)- Redis C#客户端