cs
/// <summary>
/// redis操作类
/// </summary>
public class RedisTool
{
/// <summary>
/// 构造
/// </summary>
/// <param name="configuration"></param>
public RedisTool(IConfiguration configuration)
{
string redis = configuration.GetValue<string>("redis");
CSRedisClient cSRedis = new CSRedis.CSRedisClient(redis);
RedisHelper.Initialization(cSRedis);
}
/// <summary>
/// 得到值
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string GetRedisString(string str)
{
return RedisHelper.Get(str);
}
/// <summary>
/// 得到值
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public bool SetRedisString(string key, string value)
{
return RedisHelper.Set(key, value);
}
/// <summary>
/// 设置列表
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string SetRedisList(string key, string value)
{
//列表前后插入
RedisHelper.RPush<string>(key, value).ToString();
return RedisHelper.LPush<string>(key, value).ToString();
}
/// <summary>
/// 设置哈希值
/// </summary>
/// <param name="key">表名</param>
/// <param name="field">字段名</param>
/// <param name="value">值</param>
/// <returns></returns>
public bool SetRedisHSet(string key, string field, string value)
{
//相同时会更新
return RedisHelper.HSet(key, field, value);
}
/// <summary>
/// 得到哈希值
/// </summary>
/// <param name="key"></param>
/// <param name="field"></param>
/// <returns></returns>
public string GetRedisHSet(string key, string field)
{
return RedisHelper.HGet(key, field);
}
/// <summary>
/// 给值增加指定的值
/// </summary>
/// <param name="key"></param>
/// <param name="field"></param>
/// <returns></returns>
public long SetRedisIncre(string key, long value)
{
return RedisHelper.IncrBy(key, value);
}
/// <summary>
/// 是否包含
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool RedisSIsMember(string key, string value)
{
//是否包含
return RedisHelper.SIsMember(key, value);
}
}
1、配置appsettings.json:
"redis": "127.0.0.1:6379,password=,defaultDatabase=1,poolsize=50,ssl=false,writeBuffer=10240"
2、用的大神国产包:CSRedisCore
追加消息发布和订阅示例(mq直连和广播模式):
cs
/// <summary>
/// 消息发布
/// </summary>
void Publish()
{
//RedisHelper.Publish("subscribe", "12");
RedisHelper.LPush("subscribe", "12");
}
/// <summary>
/// 消息订阅
/// </summary>
void Subscribe()
{
//SubscribeObject subscribeObject
// = RedisHelper.Subscribe(("subscribe", msg => SubscribeAction(msg.Body)));
//取消订阅
//subscribeObject.Dispose();
RedisHelper.SubscribeListBroadcast("subscribe", "1", msg => SubscribeAction(msg));
RedisHelper.SubscribeListBroadcast("subscribe", "2", msg => SubscribeAction(msg));
RedisHelper.SubscribeListBroadcast("subscribe", "3", msg => SubscribeAction(msg));
}
/// <summary>
/// 订阅到消息
/// </summary>
/// <param name="str"></param>
void SubscribeAction(string str)
{
Console.WriteLine(str);
}