一、下载第三方类库:StackExchange.Redis
Nuget收索StackExchange.Redis,点击安装即可,新增的第三方命名空间:using StackExchange.Redis;
二、StackExchange.Redis使用(使用前提是有Redis服务端:Linux Redis的安装可查看此文):
1、键值的存取:
static void Noth(string[] args)
{
string host = "192.168.117.129";
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(host);
IDatabase db = redis.GetDatabase();
db.StringSet("User", "{name:\"TOM\"}");
db.StringAppend("User", ",{name:\"JACK\"}"); string user = db.StringGet("User");
Console.WriteLine(user);
Console.Read(); }
2、事件的订阅:
发布端代码:
static void Main(string[] args)
{
string host = "192.168.117.129";
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(host);
ISubscriber db = redis.GetSubscriber();
db.Publish("c1", "");
string reader="start end";
while (reader != "exit")
{
reader = Console.ReadLine();
db.Publish("c1", reader);
}
Console.Read(); }
订阅者代码:
static void Main(string[] args)
{
string host = "192.168.117.129";
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(host);
ISubscriber db = redis.GetSubscriber();
db.Subscribe("c1",new Action<RedisChannel,RedisValue>((chan,msage)=>{
Console.WriteLine("通道:"+chan);
Console.WriteLine("消息内容:"+msage);
}));
Console.ReadLine();
}