ServiceStack.Redis使⽤教程
环境准备
在Windows上运⾏Redis服务器作开发和测试是很好的,但是在运营环境还是Linux版本靠谱,下⾯我们就先解压Redis到⼀个⽬录下:运⾏ 看到如下Windows控制台:
上⾯我们可以看到Redis运⾏的端⼝是6372
我们先玩⼀下Redis的客户端控制台,在相同⽬录下运⾏会弹出另⼀个控制台程序,可以参考开始你的交互之旅。
输⼊命令 set car.make “Ford” 添加了⼀个car.make为Key,Value是Ford的数据进⼊Redis,输⼊命令get car.make就可以取回Ford
下⾯我们进⼊正题,讲主⾓ServiceStack.Redis :
⾸先创建⼀个控制台程序,然后解压缩,然后添加下⾯的四个引⽤
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; }
}
writeline教程public class Model
{
public int Id { get; set; }
public Make Make { get; set; }
public string Name { get; set; }
}
}
例⼦代码下载:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论