一、引用dll
using StackExchange.Redis;
二、config配制连接
三、建立连接
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 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;
///
/// 订阅
///
///
public void RedisSub(string subChannel)
{
redis.GetSubscriber().Subscribe(subChannel, (channel, message) => {
RedisSubMessageEvent?.Invoke(message); //触发事件
});
}
///
/// 发布
///
///
///
///
///
public long RedisPub(string channel, T msg)
{
return redis.GetSubscriber().Publish(channel, msg.ToString());
}
///
/// 取消订阅
///
///
public void Unsubscribe(string channel)
{
redis.GetSubscriber().Unsubscribe(channel);
}
///
/// 取消全部订阅
///
public void UnsubscribeAll()
{
redis.GetSubscriber().UnsubscribeAll();
}
#endregion
- C#WinForm实操串口通讯使用GtkSharp库实现跨平台
- C#实现Modbus RTU串口之间的通讯
- C#实现ModbusTCP之间的通讯方式,解析报文
- C#实现UDP通讯
- C#实现TCP通讯
- WEB报表工具Stimulsoft Reports.Web在.NET WebForm项目中使用
- C#实现西门子S7-1200、200 SMART PLC之间通信
- C#实现WebApi接口数据传输加密方案