Redis 小测试
一、首先保证redis服务器要开启
二、新建一个控制台进行测试
1、StackExchange.Redis
using StackExchange.Redis;
using System;
using System.Threading;
class Program
{
static ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect("localhost");
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//实例化redis库
IDatabase db = redisClient.GetDatabase();
// 测试 key value
string value = "abcdefg";
//存储一个键值对 mykey:abcdefg
db.StringSet("mykey", value);
//输出mykey的值
value = db.StringGet("mykey");
Console.WriteLine(value);
// 测试消息队列
ISubscriber sub = redisClient.GetSubscriber();
sub.Subscribe("messages", (channel, message) =>
{
Console.WriteLine((string)message);
});
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
sub.Publish("messages", "hello" + i);
}
Thread.Sleep(1000);
sub.Subscribe("redisMessages", (channe2, message) =>
{
Console.WriteLine(message);
});
sub.Publish("redisMessages", "This message from C# program");
Console.ReadKey();
}
}
2、CSRedis
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
CSRedis.CSRedisClient csredis = new CSRedis.CSRedisClient("localhost,writeBuffer=10240,prefix=lu");
//初始化 RedisHelper
RedisHelper.Initialization(csredis);
RedisHelper.Set(":name", "xxx");
Console.WriteLine(RedisHelper.Get("name"));
//普通订阅
//RedisHelper.Subscribe()
RedisHelper.Subscribe(("chan1", (msg) =>
{
Console.WriteLine(msg.Body);
}
));
//模式订阅(通配符)
//RedisHelper.PSubscribe(new[] { "chan1", "chan2", "test*002" }, msg =>
//{
// Console.WriteLine($"PSUB {msg.MessageId}:{msg.Body} {msg.Pattern}: chan:{msg.Channel}");
//});
for (int i = 0; i < 20; i++)
{
Thread.Sleep(300);
RedisHelper.Publish("chan1", "hello");
}
for (int i = 0; i < 10; i++)
{
Thread.Sleep(300);
RedisHelper.Publish("chan2", "hello word");
}
}
}
以上代码可以直接复制到控制台测试
代码执行后,redis数据库中就有相应的存储