使用Redis可以优化性能,但存在Redis的数据和数据库同步的问题。前面说过redis事务不是特别可靠:在执行事务命令的时候,在命令入队的时候,redis就会检测事务的命令是否正确,如果不正确则会产生错误并进行回滚;但是当命令格式正确,而因为操作数据结构引起的错误,则该命令执行出现错误,而其之前和之后的命令都会被正常执行。这点和数据库很不一样。
但是,有些情况并不要求数据是最新的,例如显示用户购买排名榜,书籍信息等等,所以我们考虑:常用于显示的,以查询Redis为主;重要信息的读写以数据库最新信息为主。
一、redis和数据库读操作 数据缓存往往会在redis上设置超时时间,当设置redis的数据超时后,redis就无法读出数据了,这个时候就会触发程序读取数据库,然后将读取的数据写入redis并重新设置超时时间,这样程序就可以在读取的过程中按照一定的时间间隔刷新数据了。
好处:保证了一定的实时性,也避免了多次访问数据库造成的系统性能低下的情况。
二、redis和数据库写操作 写操作需要考虑数据一致的问题,写入业务数据时,先从数据库中读取最新数据,然后进行业务操作,更新业务数据到数据库,再将数据刷新到redis缓存中。
好处:避免将脏数据写入数据库中。
原文链接:https://blog.csdn.net/qq_40645822/article/details/91359078