计算机组成原理中学习过缓存一致性问题,即当多个CPU在操作自己的缓存时,可能会出现各自的缓存内容不同步的问题,而Mybatis也会这样:
public static void main(String[] args) throws InterruptedException {
try (SqlSession sqlSession = MybatisUtil.getSession(true)){
TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
while (true){
Thread.sleep(3000);
System.out.println(testMapper.getStudentBySid(1));
}
}
}
我们现在循环地每三秒读取一次,而在这个过程中,我们使用IDEA手动修改数据库中的数据,将1号同学的学号改成100,此时 Mybatis 不知道数据库内容已经被其他程序修改,因此依然会从缓存中读取。
此时有两种解决方案:
- 关闭 Mybatis 的缓存来保证一致性
<settings> <setting name="cacheEnabled" value="false"/> </settings>
<select id="getStudentBySid" resultType="Student" useCache="false" flushCache="true"> select * from student where sid = #{sid} </select>
- 需要实现缓存共用,也就是让所有的Mybatis都使用同一个缓存进行数据存取 在后面,我们会继续学习Redis、Ehcache、Memcache等缓存框架,通过使用这些工具,就能够很好地解决缓存一致性问题。