using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace Quiz.SiteBase
{
public class RedisHelper
{
private readonly static string REDIS_CONN = "121.40.109.21:6379,password=123456";
private readonly static string REDIS_IP = "121.40.109.21";
private readonly static int REDIS_PORT = 6379;
private ConnectionMultiplexer redis = null;
private IDatabase database = null;
private IServer server = null;
private int mydb = 0;
public RedisHelper(int db)
{
mydb = db;
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(REDIS_CONN);
database = redis.GetDatabase(mydb);
server = redis.GetServer(REDIS_IP, REDIS_PORT);
redis.ErrorMessage += Redis_ErrorMessage;
}
}
///
/// 异常记录
///
///
///
private static void Redis_ErrorMessage(object sender, RedisErrorEventArgs e)
{
//LogHelper.WriteLog("Redis", new Exception(e.Message));
}
///
/// 通过key获取value
///
///
///
public string StringGet(string key)
{
return database.StringGet(key);
}
///
/// 新增key value
///
///
///
///
///
public bool StringSet(string key, string val, TimeSpan? exp = default(TimeSpan?))
{
return database.StringSet(key, val, exp);
}
///
/// 新增key value
///
///
///
///
///
public bool ObjectSet(string key, object val, TimeSpan? exp = default(TimeSpan?))
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(val);
return database.StringSet(key, json, exp);
}
///
/// 获取key
///
///
///
public IEnumerable LikeKeys(string pattern = "*")
{
return server.Keys(database: mydb, pattern: pattern);
}
///
/// 查询
///
///
///
public Dictionary GetLikeKeyValue(string pattern = "*")
{
IEnumerable list = LikeKeys(pattern);
Dictionary dic = new Dictionary();
if (list != null && list.Count() > 0)
{
foreach (var item in list)
{
dic.Add(item, StringGet(item));
}
}
return dic;
}
///
/// 删除key
///
///
///
public bool KeyDelete(string key)
{
return database.KeyDelete(key);
}
}
}