凯尔瑞斯

导航

C# Redis Server分布式缓存编程 --网络转载

这篇文章我将介绍如果用最简洁的方式配置Redis Server,

以及如何使用C#和它交互编程

一. 背景介绍

Redis是最快的key-value分布式缓存之一

缺点: 没有本地数据缓冲, 目前还没有完整的数据聚集化支持

优点: 配置简单, 使用方便, 高性能,支持不同的数据类型(hashes, lists, sets, sorted sets)

        ASP.NET WebUI for viewing content of the cache

 

二. 安装Redis

1) 从github下载最新的32/64位安装

https://github.com/dmajkic/redis/downloads

解压到你自己的目录

eg: d:\RedisServer

 

2) 从github下载Redis服务程序

dll手工版

https://github.com/kcherenkov/redis-windows-service/downloads

 

安装版

https://github.com/rgl/redis/downloads

 

拷贝到RedisServer的安装目录

eg: d:\RedisServer

 

3) 安装redis服务

进入你的应用程序目录,运行下面的命令

sc create %name% binpath= "\"%binpath%\" %configpath%" start= "auto" DisplayName= "Redis"

 

%name% -- name of service instance, ex. redis-instance;

%binpath% -- path to this project exe file, ex. C:\Program Files\Redis\RedisService_1.1.exe;

%configpath% -- path to redis configuration file, ex. C:\Program Files\Redis\redis.conf; 

 

sc create my-redis binpath= "\"D:\RedisServer\RedisService_1.1.exe\"  D:\RedisServer\redis.conf" start= "auto" DisplayName= "MyRedis"

 

 

 

4) 基本配置

redis.conf

# requirepass foobared  

去掉注释,重启服务

这样实例化一个Redis服务的时候,就需要密码

RedisClient client = new RedisClient(serverHost, port, redisPassword);

Redis server replication (master - slave配置)

# slaveof <masterip> <masterport>

eg:

slaveof 192.168.1.1 6379

 

三. 客户端编程

1) 安装Redis包

 

2) 简单例子

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using System.Threading;

namespace Zeus.Cache.Redis.Demo
{
    public class SimpleRedisDemo
    {
        public void SimpleDemo()
        {
            string host = "localhost";
            string elementKey = "testKeyRedis";

            using (RedisClient redisClient = new RedisClient(host))
            {
                if (redisClient.Get<string>(elementKey) == null)
                {
                    // adding delay to see the difference
                    Thread.Sleep(2000);
                    // save value in cache
                    redisClient.Set(elementKey, "default value");
                }

                //change the value
                redisClient.Set(elementKey, "fuck you value");

                // get value from the cache by key
                string message = "Item value is: " + redisClient.Get<string>(elementKey);

                Console.WriteLine(message);
            }
        }
    }
}
复制代码

运行结果:

posted on 2016-07-27 18:23  凯尔瑞斯  阅读(154)  评论(0编辑  收藏  举报