Cache_Redis_2使用
1.StackExchange.Redis 中最重要的对象 是 ConenctionMultiplexer .
存在于命名空间 StackExchagne.Redis 命名空间中。
2.ConnectionMultiplexer .
在所有调用中,被设计成共享和重用的。不应该为每一个操作都创建一个ConnectionMultiplexer对象。
ConnectionMultiplexer是线程安全的。
假定已经实例化了一个ConnectionMultiplexer ,并将被一直重用。
(1)创建
通过 ConnectionMultiplexer.Connect 或者 ConnectionMultiplexer.ConnectAsync,传递一个字符串或CongiurationOptions类创建。
using StackExchange.Redis;
...
ConnectionMultiplexer redis=ConnectionMultiplexer.Connection("localhost");
(2)访问数据库
IDatabase db=redis.GetDatabase();
(3)操作
StringSet,StringGet,
3.ConnectionMultiplexer实例
--引用dll: StackExchange.Redis
--创建链接,实例化ConnectionMultiplexer.
public class RedisCacheManager:ICacheManager{
private readonly string redisConnectionString;
public volatile ConnectionMultiplexer redisConnection;
private readonly object redisConnectionLock=new object();
public RedisCacheManager(){
string redisConfiguration=ConfigurationManager.ConnectionStrings["redisCache"].ToString();
if(string.IsNullOrEmpty(redisConfiguration)){
throw new ArgumentException(" redis config is empty",nameof(redisConfiguration));
}
this.redisConnectionString=redisConfiguration;
this.redisConnection=GetRedisConnection();
}
private ConnectionMultiplexer GetRedisConnection(){
if(redisConnection!=null&&redis.Connection.IsActive){
return this.redisConnection;
}
lock(redisConnectionLock){
if(this.redisConnection!=null){
this.redisConnection.Dispose();
}
this.redisConnection=ConnectionMultiplexer.Connect(redisConnectionString);
}
return this.redisConnection;
}
public void Set(string key,object value,TimeSpan cacheTime){
if(value!=null){
this.redisConnection.GetDatabase().StringSet(key,SerializerHelper.Serialize(value),cacheTime);
}
}
public T Get<T>(string key){
var value=this.redisConnection.GetDatabase().StringGet(key);
if(value.HasValue){
return SerializerHelper.Deserialize<T>(value);
}else{
return string.Empty;
}
}
public void Contains(string key){
return this.redisConnection.GetDatabase().KeyExists(key);
}
public void Remove(string key){
this.redisConnection.GetDatabse().KeyDelete(key);
}
}