这篇文章主要讲解了“redis数据库的简单用法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“redis数据库的简单用法”吧!
创新互联是一家专业提供新源企业网站建设,专注与做网站、成都网站制作、H5网站设计、小程序制作等业务。10年已为新源众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
///
/// Redis 操作类
///
public class RedisHelper
{
///
/// 连接字符串
///
private static readonly string ConnectionString = ConfigurationManager.AppSettings["RedisConnectionString"];
///
/// 锁
///
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 _connection.GetDatabase(db ?? -1);
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
{
var rValue = _db.StringGet(key);
if (!rValue.HasValue)
{
return default(T);
}
var result = Deserialize
return result;
}
///
/// 反序列化
///
///
///
///
protected virtual T Deserialize
{
if (serializedObject == null)
{
return default(T);
}
var json = Encoding.UTF8.GetString(serializedObject);
return JsonConvert.DeserializeObject
}
///
/// 判断是否已经设置
///
///
///
public virtual bool IsSet(string key)
{
return _db.KeyExists(key);
}
///
/// 序列化
///
///
///
private byte[] Serialize(object data)
{
var json = JsonConvert.SerializeObject(data);
return Encoding.UTF8.GetBytes(json);
}
}
}
感谢各位的阅读,以上就是“redis数据库的简单用法”的内容了,经过本文的学习后,相信大家对redis数据库的简单用法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!
本文题目:redis数据库的简单用法
当前URL:http://scyingshan.cn/article/jsoscd.html