环境准备
- Redis (使用Windows版本做测试,运营环境建议使用Linux版本)
- ServiceStack.Redis-v3.00
在Windows上运行Redis服务器作开发和测试是很好的,但是在运营环境还是Linux版本靠谱,下面我们就先解压Redis到一个目录下:
运行redis-server.exe 看到如下Windows控制台:
上面我们可以看到Redis运行的端口是6372
我们先玩一下Redis的客户端控制台,在相同目录下运行redis-cli.exe会弹出另一个控制台程序,可以参考Try Redis tutorial开始你的交互之旅。
输入命令 set car.make “Ford” 添加了一个car.make为Key,Value是Ford的数据进入Redis,输入命令get car.make就可以取回Ford
下面我们进入正题,讲主角ServiceStack.Redis :
首先创建一个控制台程序,然后解压缩ServiceStack.Redis-v3.00.zip ,然后添加下面的四个引用
- ServiceStack.Common
- ServiceStack.Interfaces
- ServiceStack.Redis
- ServiceStack.Text
我们下面来写些代码,创建一个Car类并存储几个实例到Redis,然后让一个对象5秒后过期,等待6秒钟后输出Car的实例数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using System.Threading;
namespace RedisTutorial
{
class Program
{
static void Main(string[] args)
{
var redisClient = new RedisClient("localhost");
using (var cars = redisClient.GetTypedClient
{
if (cars.GetAll().Count > 0)
cars.DeleteAll();
var dansFord = new Car
{
Id = cars.GetNextSequence(),
Title = "Dan's Ford",
Make = new Make { Name = "Ford" },
Model = new Model { Name = "Fiesta" }
};
var beccisFord = new Car
{
Id = cars.GetNextSequence(),
Title = "Becci's Ford",
Make = new Make { Name = "Ford" },
Model = new Model { Name = "Focus" }
};
var vauxhallAstra = new Car
{
Id = cars.GetNextSequence(),
Title = "Dans Vauxhall Astra",
Make = new Make { Name = "Vauxhall" },
Model = new Model { Name = "Asta" }
};
var vauxhallNova = new Car
{
Id = cars.GetNextSequence(),
Title = "Dans Vauxhall Nova",
Make = new Make { Name = "Vauxhall" },
Model = new Model { Name = "Nova" }
};
var carsToStore = new List
cars.StoreAll(carsToStore);
Console.WriteLine("Redis Has-> " + cars.GetAll().Count + " cars");
cars.ExpireAt(vauxhallAstra.Id, DateTime.Now.AddSeconds(5)); //Expire Vauxhall Astra in 5 seconds
Thread.Sleep(6000); //Wait 6 seconds to prove we can expire our old Astra
Console.WriteLine("Redis Has-> " + cars.GetAll().Count + " cars");
//Get Cars out of Redis
var carsFromRedis = cars.GetAll().Where(car => car.Make.Name == "Ford");
foreach (var car in carsFromRedis)
{
Console.WriteLine("Redis Has a ->" + car.Title);
}
}
Console.ReadLine();
}
}
public class Car
{
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Make Make { get; set; }
public Model Model { get; set; }
}
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Model
{
public int Id { get; set; }
public Make Make { get; set; }
public string Name { get; set; }
}
}
例子代码下载:RedisTutorial.zip
ServiceStack.Redis的问题与修正
性能测试:Redis千万级的数据量的性能测试
几点建议,让Redis在你的系统中发挥更大作用
Redis