各類redis的介紹:ServiceStack.Redis,StackExchange.Redis,CSRedis

 

1.ServiceStack.Redis 是商業版,免費版有限制;ServiceStack.Redis每小時6000次限制,ServiceStack 4.0 開始已經成爲商業產品,再也不徹底免費,好在是開源的.mysql

2.StackExchange.Redis 是免費版,可是內核在 .NETCore 運行有問題常常 Timeout,暫沒法解決;redis

3.CSRedis於2016年開始支持.NETCore一直迭代至今,實現了低門檻、高性能,和分區高級玩法的.NETCore redis-cli SDK;sql

 

1. 經過包管理器安裝CSRedis
2. 實例化csredis,並繼承icasheservice
3. DBContent 裏實例化csredisClient
4. TestRedisCache數據庫


public class TestRedisCache: ICacheService
{
/// <summary>
/// redis
/// </summary>
public CSRedisClient rds;json

//redis cach second,default 120,read appsetting.json
int _expirySeconds = 120;
/// <summary>
/// 構造函數
/// </summary>
/// <param name="connectionStrings"></param>
public TestRedisCache(string[] connectionStrings, int expirySeconds)
{
this.rds = new CSRedis.CSRedisClient((p => { return null; }), connectionStrings);
_expirySeconds = expirySeconds;
}緩存

public void Add<V>(string key, V value)
{
this.rds.Set(key, value);app

}異步

public void Add<V>(string key, V value, int cacheDurationInSeconds)
{
if (cacheDurationInSeconds >= 2147483647)
{
cacheDurationInSeconds = _expirySeconds;
}
this.rds.Set(key, value, cacheDurationInSeconds);
}ide

public bool ContainsKey<V>(string key)
{
return this.rds.Exists(key);
}函數

public V Get<V>(string key)
{
return this.rds.Get<V>(key);
}

public IEnumerable<string> GetAllKey<V>()
{
return this.rds.Keys("*");
}

public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
{
if (this.ContainsKey<V>(cacheKey))
{
return this.Get<V>(cacheKey);
}
else
{
var result = create();
this.Add(cacheKey, result, cacheDurationInSeconds);
return result;
}
}

public void Remove<V>(string key)
{
this.rds.Del(key);
}
public void DisposeRedis()
{
this.rds.Dispose();
}
}
}


5. DBContext

public DBContext()
{
//get mysql connnection str
var salveCount = configuration.GetSection("ConnectionStrings:SlaveCount").Value.ObjToInt();
List<SlaveConnectionConfig> slaves = new List<SlaveConnectionConfig>();
for (int i = 0; i < salveCount; i++)
{
slaves.Add(new SlaveConnectionConfig
{
ConnectionString = configuration[$"ConnectionStrings:Slave:{i}:ConnectionString"], HitRate = configuration[$"ConnectionStrings:Slave:{i}:HitRate"].ObjToInt()
});
}

//redis db default expiration Second
if (!string.IsNullOrEmpty(configuration["RedisString:DurationSecond"]))
{ CachExpirationSecond = int.Parse(configuration["RedisString:DurationSecond"]); }

string redisconn = configuration["RedisString:ConnectionHost"];

if (RedisDB == null)
{
RedisDB = new ExamRedisCache(new string[] { redisconn }, CachExpirationSecond);
}


//mysql db object
if (DB == null)
{
DB = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = configuration["ConnectionStrings:Master"],
DbType = DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
SlaveConnectionConfigs = slaves,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = RedisDB
}
});
}

//調式代碼 用來打印SQL
DB.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql + "\r\n" +
DB.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
Console.WriteLine();
};
}

 

-----------------csRedis-------------

void Test()
{

CsRedisHelper.Set("name", "祝雷");//設置值。默認永不過時
//aaaaa.SetAsync("name", "祝雷");//異步操做
Console.WriteLine(CsRedisHelper.Get<String>("name"));

CsRedisHelper.Set("time", DateTime.Now, 1);
Console.WriteLine(CsRedisHelper.Get<DateTime>("time"));

Console.WriteLine(CsRedisHelper.Get<DateTime>("time"));

// 列表
CsRedisHelper.RPush("list", "第一個元素");
CsRedisHelper.RPush("list", "第二個元素");
CsRedisHelper.LInsertBefore("list", "第二個元素", "我是新插入的第二個元素!");
Console.WriteLine($"list的長度爲{CsRedisHelper.LLen("list")}");
//Console.WriteLine($"list的長度爲{aaaaa.LLenAsync("list")}");//異步
Console.WriteLine($"list的第二個元素爲{CsRedisHelper.LIndex("list", 1)}");
//Console.WriteLine($"list的第二個元素爲{aaaaa.LIndexAsync("list",1)}");//異步
// 哈希
CsRedisHelper.HSet("person", "name", "zhulei");
CsRedisHelper.HSet("person", "sex", "男");
CsRedisHelper.HSet("person", "age", "28");
CsRedisHelper.HSet("person", "adress", "hefei");
Console.WriteLine($"person這個哈希中的age爲{CsRedisHelper.HGet<int>("person", "age")}");
//Console.WriteLine($"person這個哈希中的age爲{aaaaa.HGetAsync<int>("person", "age")}");//異步


// 集合
CsRedisHelper.SAdd("students", "zhangsan", "lisi");
CsRedisHelper.SAdd("students", "wangwu");
CsRedisHelper.SAdd("students", "zhaoliu");
Console.WriteLine($"students這個集合的大小爲{CsRedisHelper.SCard("students")}");
Console.WriteLine($"students這個集合是否包含wagnwu:{CsRedisHelper.SIsMember("students", "wangwu")}");

//普通訂閱
RedisHelper.Subscribe(
("chan1", msg => Console.WriteLine(msg.Body)),
("chan2", msg => Console.WriteLine(msg.Body)));

//模式訂閱(通配符)
RedisHelper.PSubscribe(new[] { "test*", "*test001", "test*002" }, msg => {
Console.WriteLine($"PSUB {msg.MessageId}:{msg.Body} {msg.Pattern}: chan:{msg.Channel}");
});
//模式訂閱已經解決的難題:
//一、分區的節點匹配規則,致使通配符最大可能匹配所有節點,因此所有節點都要訂閱
//二、本組 "test*", "*test001", "test*002" 訂閱所有節點時,須要解決同一條消息不可執行屢次

//發佈
RedisHelper.Publish("chan1", "123123123");
//不管是分區或普通模式,RedisHelper.Publish 均可以正常通訊

//不加緩存的時候,要從數據庫查詢
//var t1 = Test.Select.WhereId(1).ToOne();

//通常的緩存代碼,如不封裝還挺繁瑣的
var cacheValue = RedisHelper.Get("test1");
if (!string.IsNullOrEmpty(cacheValue))
{
//try
//{
// return JsonConvert.DeserializeObject(cacheValue);
//}
//catch
//{
// //出錯時刪除key
// RedisHelper.Del("test1");
// throw;
//}
}
//var t1 = Test.Select.WhereId(1).ToOne();
// RedisHelper.Set("test1", JsonConvert.SerializeObject(t1), 10); //緩存10秒

//使用緩存殼效果同上,如下示例使用 string 和 hash 緩存數據 //var t1 = RedisHelper.CacheShell("test1", 10, () => Test.Select.WhereId(1).ToOne()); //var t2 = RedisHelper.CacheShell("test", "1", 10, () => Test.Select.WhereId(1).ToOne()); //var t3 = RedisHelper.CacheShell("test", new[] { "1", "2" }, 10, notCacheFields => new[] { // ("1", Test.Select.WhereId(1).ToOne()), // ("2", Test.Select.WhereId(2).ToOne()) // }); }

相關文章
相關標籤/搜索