C#操作Redis实现读写、订阅发布功能
|
admin
2025年1月6日 21:36
本文热度 132
|
一、引用dll
using StackExchange.Redis;
二、config配制连接
<appSettings>
<add key="RedisConnectionString" value="192.168.200.84:6379,password=123456,abortConnect=false" />
</appSettings>
三、建立连接
private static ConnectionMultiplexer redis = null;
private static bool connected = false;
private IDatabase db = null;
private int current = 0;
public static bool IsConnected { get { Open(); return redis.IsConnected; } }
private static Configuration config = new Configuration();
private static int Open()
{
if (connected) return 1;
redis = ConnectionMultiplexer.Connect(config.GetAppSetting("RedisConnectionString"));
connected = true;
return 1;
}
public static void Using(Action<Redis> a)
{
using (var red = new Redis())
{
a(red);
}
}
public Redis Use(int i)
{
Open();
current = i;
db = redis.GetDatabase(i);
var t = db.Ping();
return this;
}
四、redis读写删操作
#region Redis缓存
public void Set(string key, string val, TimeSpan? ts = null)
{
db.StringSet(key, val, ts);
}
public string Get(string key)
{
return db.StringGet(key);
}
public void Remove(string key)
{
db.KeyDelete(key, CommandFlags.HighPriority);
}
public bool Exists(string key)
{
return db.KeyExists(key);
}
public void Dispose()
{
db = null;
}
#endregion
五、redis发布订阅
#region Redis发布订阅
public delegate void RedisDeletegate(string str);
public event RedisDeletegate RedisSubMessageEvent;
/// <summary>
/// 订阅
/// </summary>
/// <param name="subChannel"></param>
public void RedisSub(string subChannel)
{
redis.GetSubscriber().Subscribe(subChannel, (channel, message) => {
RedisSubMessageEvent?.Invoke(message); //触发事件
});
}
/// <summary>
/// 发布
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel"></param>
/// <param name="msg"></param>
/// <returns></returns>
public long RedisPub<T>(string channel, T msg)
{
return redis.GetSubscriber().Publish(channel, msg.ToString());
}
/// <summary>
/// 取消订阅
/// </summary>
/// <param name="channel"></param>
public void Unsubscribe(string channel)
{
redis.GetSubscriber().Unsubscribe(channel);
}
/// <summary>
/// 取消全部订阅
/// </summary>
public void UnsubscribeAll()
{
redis.GetSubscriber().UnsubscribeAll();
}
#endregion
阅读原文:原文链接
该文章在 2025/1/7 11:47:56 编辑过