public class RedisHelper
{
RedisClient redis = Redis_Client.GetRedis();
public int AddUserInfo(string userKey,UserInfo mod)
{
//判断key是否存在
if (!redis.ContainsKey(userKey))
{
List<UserInfo> list = new List<UserInfo>();
try
{
mod.UId = 1;
//list添加值
list.Add(mod);
//注册信息保存到Redis数据库中
redis.Set(userKey, list);
return list.Count;
}
catch (Exception)
{
return 0;
}
}
else
{
//获取redis缓存用户列表数据
var list = GetUserInfos(userKey);
try
{
//UId自增
mod.UId = list.OrderByDescending(m => m.UId).FirstOrDefault().UId+1;
list.Add(mod);
//缓存赋值
redis.Set(userKey, list);
return list.Count;
}
catch (Exception)
{
return 0;
}
}
}
//获取Redis缓存用户列表数据
public List<UserInfo> GetUserInfos(string userKey)
{
return redis.Get<List<UserInfo>>(userKey);
}
}
`` /// <summary>
/// 单例模式配置Redis服务器
/// </summary>
public class Redis_Client
{
//私有构造函数
private Redis_Client() { }
//私有静态字段
private static RedisClient redis;
//安全锁
private static object Lock = new object();
//公用静态方法
public static RedisClient GetRedis()
{
//验证是否为空
if (redis==null)
{
//安全锁双重验证
lock (Lock)
{
if (redis==null)
{
//配置Redis
redis = new RedisClient("127.0.0.1", 6379);
return redis;
}
}
}
return redis;
}
}