環境准備
在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<Car>())
{
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<Car> { dansFord, beccisFord, vauxhallAstra, vauxhallNova };
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