.NET 中使用redis(三)
1,既然redis是存在内存中的,那如果查询数据是从服务器内存中读取出来速度是很快的,同时减轻了数据库的压力,尤其数据量很大是时候的查询!!
2,简答的思路是,redis在客户端和数据库之间,获取数据是从redis中获取!!
3,但是这样有个问题,数据库中和redis中的数据可能不同,一旦有数据新增,删除,修改那么就同样的查询条件在redis和数据中查询出来就是不同的。
方案1:一旦有数据新增,删除,修改,那么删除对应的key然后通过数查询后给到对应的key中,(这样操作比较大,适合大量数据批量操作)
方案2:一旦有数据新增,删除,修改,同步执行操作在redis 的数据,同时快速查询redis返回数据显示
4,小例子
public ActionResult Index()
{
////1.连接redis 内存数据库(IP地址,redis的端口,密码)
RedisClient redisClient = new RedisClient(“127.0.0.1”, 6379, “666”);
bool isUserKey = redisClient.ContainsKey("user"); //是否存在key
if (isUserKey == false) //redis中没有数据
{
textEntities contex = new textEntities(); //EF上下文对象
List<Users> listUser = contex.Users.Where(p => p.uid > 10).ToList(); //获取 sql server中的数据
redisClient.Set("user", listUser); //获取 sql server中的数据给到redis 中
redisClient.Expire("user", 5); //5秒钟后自动过期,过期之后 肯定是没有了 user 这个key 那么用户过5秒之后请求,则isUserKey==false
}
ViewBag.Commod = redisClient.Get<List<Users>>("user");
return View();
}
//前端代码
@using testRedis;
@{
ViewBag.Title = "Index";
List<Users> comd = ViewBag.Commod;
}
<table>
@foreach (Users item in comd)
{
<tr role="row">
<td>@item.uid</td>
<td>@item.name</td>
<td>@item.pwd</td>
<td>@item.power</td>
</tr>
}
</table>
//删除,新增,修改等操作
public ActionResult delete(int uid, string key) //为了实现同步的效果,每次在数据在增加,修改,删除之后,删除对应的key,然后重新把值重新给定
{
////1.连接redis 内存数据库(IP地址,redis的端口,密码)
RedisClient redisClient = new RedisClient("127.0.0.1", 6379, "666");
textEntities contex = new textEntities();
contex.Users.Remove(new Users { uid = uid });
int res = contex.SaveChanges();
if (res > 0) //修改成功啊,返回对应数据
{
List<Users> listUser = contex.Users.ToList(); //获取真实数据库中的对象集合
if (redisClient.ContainsKey(key))
{
redisClient.Del(key); //删除对应的key,重新给key赋值
}
bool setOK = redisClient.Set(key, listUser); //更新后的数据然后存在redis中
ViewBag.Commod = redisClient.Get<List<Users>>(key); //返回数据
}
return null;
}
暂时写到这,方案二的思路也很简单,欢迎指点!!