Redis(二):c#连接Redis
标签:oid new conf type var 反序列化 对象 base object
1、nuget StackExchange.Redis
2、建立RedisHelper类:
public class RedisHelper
{
///
/// 连接字符串
///
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString;
///
/// 锁
///
private readonly object _lock = new object();
///
/// 连接对象
///
private volatile IConnectionMultiplexer _connection;
///
/// 数据库
///
private IDatabase _db;
public RedisHelper()
{
_connection = ConnectionMultiplexer.Connect(ConnectionString);
_db = GetDatabase();
}
///
/// 获取连接
///
///
protected IConnectionMultiplexer GetConnection()
{
if (_connection != null && _connection.IsConnected)
{
return _connection;
}
lock (_lock)
{
if (_connection != null && _connection.IsConnected)
{
return _connection;
}
if (_connection != null)
{
_connection.Dispose();
}
_connection = ConnectionMultiplexer.Connect(ConnectionString);
}
return _connection;
}
///
/// 获取数据库
///
///
///
public IDatabase GetDatabase(int? db = null)
{
return GetConnection().GetDatabase(db ?? -1);
}
///
/// 设置
///
/// 键
/// 值
/// 时间
public virtual void Set(string key, object data, int cacheTime)
{
if (data == null)
{
return;
}
var entryBytes = Serialize(data);
var expiresIn = TimeSpan.FromMinutes(cacheTime);
_db.StringSet(key, entryBytes, expiresIn);
}
///
/// 根据键获取值
///
///
///
///
public virtual T Get(string key)
{
var rValue = _db.StringGet(key);
if (!rValue.HasValue)
{
return default(T);
}
var result = Deserialize(rValue);
return result;
}
///
/// 反序列化
///
///
///
///
protected virtual T Deserialize(byte[] serializedObject)
{
if (serializedObject == null)
{
return default(T);
}
var json = Encoding.UTF8.GetString(serializedObject);
return JsonConvert.DeserializeObject(json);
}
///
/// 判断是否已经设置
///
///
///
public virtual bool IsSet(string key)
{
return _db.KeyExists(key);
}
///
/// 序列化
///
///
/// byte[]
private byte[] Serialize(object data)
{
var json = JsonConvert.SerializeObject(data);
return Encoding.UTF8.GetBytes(json);
}
}
3、查看远程Redis端口是否开放:
如果没有开放的话,请修改Redis的conf文件的bind:127.0.0.1 改为 bind 0.0.0.0
Redis(二):c#连接Redis
标签:oid new conf type var 反序列化 对象 base object
原文地址:https://www.cnblogs.com/25miao/p/9931925.html
评论