Redis——分布式简单使用

Redis简介:Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

Redis安装:参考博客http://www.cnblogs.com/hoojo/p/4466024.html

Redis在C#中的使用:

1.首先引用C#驱动程序 驱动下载:http://pan.baidu.com/s/1miTdvE4

2.通过VS中的NuGet添加Redis的客户端

3.编写代码

Demo1演示:

最基本的使用:

运行图:

  //Redis基本用法
            var client = new RedisClient("127.0.0.1",6379);
            client.Set<int>("num1", 1111);
            client.Set<string>("str1", "hhhh");
            int num1 = client.Get<int>("num1");
            string str1 = client.Get<string>("str1");
            Console.WriteLine(num1);
            Console.WriteLine(str1);
            Console.ReadKey();

 

Demo2演示:

运行图:

代码:

    static void Main(string[] args)
        {    //结合Class对象使用
            Person p = new Person() { Name="RYJ",Age=22};
            //创建客户端对象
            var client = new RedisClient("127.0.0.1", 6379);
            client.Set<Person>("p1", p);
            var rec = client.Get<Person>("p1");
            Console.WriteLine(rec.Name+":"+rec.Age);
            Console.ReadKey();
        }
  class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

 

--------创建Redis【端口】和【服务】的步骤如下:

以创建6380端口为例:

首先复制一份redis.conf并重命名为redis6380.conf,然后修改里面的port为6380 --设置端口

然后开始安装:(利用管理员身份打开控制台,运行下面命令即可,注意修改成自己对应的盘符和文件名方可正常运行哦) --配置成服务

F:\redis\redis-server.exe --service-install F:\redis\redis6380.conf --service-name redisService6380 --port 6380

 

下面是简要截图:

-------利用cmd窗体命令调用服务器方法:

 

--------配置主从关系 

打开.conf文件,将# slaveof <masterip> <masterport>改为

slaveof 127.0.0.1 6379 #指定master 的ip 和端口 

 参考博客:http://www.cnblogs.com/stephen-liu74/archive/2012/04/16/2370212.html

--------------------------

以上是简单的使用,要想真正的使用,最好使用RedisCacheHelper进行操作数据,类的定义如下:

using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Redis的使用
{
    public class RedisCacheHelper
    {
        private static readonly PooledRedisClientManager pool = null;
        private static readonly string[] redisHosts = null;
        public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);
        public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);
        static RedisCacheHelper()
        {
            var redisHostStr = ConfigurationManager.AppSettings["redis_server_session"];

            if (!string.IsNullOrEmpty(redisHostStr))
            {
                redisHosts = redisHostStr.Split(',');

                if (redisHosts.Length > 0)
                {
                    pool = new PooledRedisClientManager(redisHosts, redisHosts,
                        new RedisClientManagerConfig()
                        {
                            MaxWritePoolSize = RedisMaxWritePool,
                            MaxReadPoolSize = RedisMaxReadPool,
                            AutoStart = true
                        });
                }
            }
        }
        public static void Add<T>(string key, T value, DateTime expiry)
        {
            if (value == null)
            {
                return;
            }

            if (expiry <= DateTime.Now)
            {
                Remove(key);

                return;
            }

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

        }

        public static void Add<T>(string key, T value, TimeSpan slidingExpiration)
        {
            if (value == null)
            {
                return;
            }

            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key);

                return;
            }

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

        }



        public static T Get<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 static void Remove(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Remove(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
            }

        }

        public static bool Exists(string key)
        {
            try
            {
                if (pool != null)
                {
                    using (var r = pool.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }

            return false;
        }
    }
}
View Code

上面的帮助类中用到的配置如下:

 <appSettings>
    <!-- redis Start   -->  
    <add key="redis_server_session" value="127.0.0.1:6379" />
    <add key="redis_max_read_pool" value="3" />
    <add key="redis_max_write_pool" value="1" />
    <!--redis end-->
  </appSettings>
View Code

调用Help类的示例如下:

  static void Main(string[] args)
        {
            RedisCacheHelper.Add<string>("hello", "world",DateTime.Now.AddDays(1));
            string rec = RedisCacheHelper.Get<string>("hello");
            Console.WriteLine("输出world");
            Console.WriteLine(rec);
            Console.ReadKey();
        }
View Code

-------上面主要介绍了Redis的使用,那么如何来持久化呢? 持久化有两种:第一种是定时进行持久化。第二种采用aof,当内存中有了数据就会进行持久化。这种虽然防止了数据的丢失,但减少了效率。

共同点:都是通过配置“redis.windows.conf”文件来实现的。

1.定时持久化(配置参考如下)

save 900 1 #900秒内如果超过1个key被修改,则发起快照保存
save 300 10 #300秒内容如超过10个key被修改,则发起快照保存
save 60 10000

2.Append-only file(AOF)(配置参考如下)

appendonly yes           #启用aof持久化方式
# appendfsync always   #每次收到写命令就立即强制写入磁盘,最慢的,但是保证完全的持久化,不推荐使用
appendfsync everysec     #每秒钟强制写入磁盘一次,在性能和持久化方面做了很好的折中,推荐

# appendfsync no    #完全依赖os,性能最好,持久化没保证

----------以上内容是对持久化的配置操作

Redis介绍ZJ。。。。

 

posted @ 2016-05-04 20:32  shuai7boy  阅读(520)  评论(0)    收藏  举报