目录
一、什么是缓存
缓存(cache)是指数据交换的缓冲区,当应用程序需要读取数据时,先从数据库中将数据取出,放置在 缓冲区中,应用程序从缓冲区读取数据。
在我们之前学习javase 中也存在缓存 当我们学习io流时就引入了缓存这一定义,它的存在呢主要要是使用缓冲区(buffer),我们在调用字符流、字节流的构造方法时就会底层就会创建一个长度为8192的byte数组。将读取的数据放在缓冲区的数组中,在取数据的时候就直接在缓冲区中将对应位置的数组转换为字符就可以啦。
我们在Test01中创建缓冲字节输出流在Test02中读取时就会读取到“我是中国人”
public class Test01 {
public static void main(String[] args) throws IOException {
//创建了一个缓冲字节输出流对象 1024指的是size 我们可以设置大小
OutputStream os = new BufferedOutputStream(new FileOutputStream("a.txt"),1024);
os.write("我是中国人".getBytes());
// 刷新流
os.flush();
// 关闭流
// os.close();
}
}
public class Test02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
InputStream is = new BufferedInputStream(fis);
byte[] b = new byte[1024];
int len = is.read(b);
String str = new String(b,0,len);
System.out.println(str);
is.close();
fis.close();
}
}
二、缓存的好处及缺点
好处:
cache:数据库取出的数据保存在内存中,具备快速读取和使用。
buffer:减少磁盘的读写次数,再加上计算机对缓冲区的操作大大快于对磁盘的操作,故应用缓冲区可大大提高计算机的运行速度。
缺点:
因为它们都是将内容读取了占为己有,你使用的时候再给你,所以就会存在一个数据不是最新的一个弊端,所以在一些适用场合就会有限制。
三、 存(cache)与缓冲(buffer)的主要区别
Buffer的核心作用是用来缓冲,缓和冲击(对输出设备的冲击,包括磁盘、打印机、显示器)偏重于写。
Cache的核心作用是加快取用的速度(加快读取速度,包括CPU读内存、内存读磁盘、用户通过浏览器请求资源)偏重于读。
四、Mybaits中缓存分为什么?
1、一级缓存
1.1 概念:会话 session 级别的缓存,针对一次会话操作内
(“会话技术”--------->相当于‘通电话’一样)
public class Demo3 {
public static void main(String[] args) {
SqlSession sqlSession1 = DaoUtil.getSqlSession();
StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
Student s1 = mapper1.findStudentBysid(5);
System.out.println(s1);
Student s2 = mapper1.findStudentBysid(5);
System.out.println(s2);
DaoUtil.closeResource(sqlSession1);
System.out.println(s1 == s2);
DaoUtil.closeResource(sqlSession1);
//获取新的sqlsession
SqlSession sqlSession2 = DaoUtil.getSqlSession();
StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
Student s3 = mapper2.findStudentBysid(5);
System.out.println(s3);
DaoUtil.closeResource(sqlSession2);
System.out.println(s1 == s3);
}
}
上述第二个s1!=s3 打印为false的原因就是因为一级缓存失效了,而一级缓存失效的情况还有以下几种
1.2一级缓存失效
a.用的不是同一条sqlsession
b.用的是不同的sql语句
c.进行增 删 改 查 后
d.清空缓存 sqlsession。clearcache()
2、二级缓存(不建议使用)
概念:一个 namespace 下的所有操作语句,都影响着同一个Cache
二级缓存的配置方法
//1、在接口的定义上面直接使用@CacheNamespace 并将blocking设置为true
//2、在mybatis的sqlMapConfig.xml 中配置
// <select name="cacheEnabled" value="true">
@CacheNamespace(blocking = true)
public interface StudentMapper {
// 缓存
@Select("select * from student where sid = #{v}")
public Student findStudentBysid(int sid);
}
3、自定义缓存的方式
1.实现 org. apache. ibatis. cache. Cache 接口自定义缓存;
五、一级缓存和二级缓存的区别
一级缓存 | 二级缓存 |
1、作用域的不同 | |
当前sqlsession对象 | 当前SQL sessionFactrory工厂 所生产的所有sqlsession对象 |
2、开启方式不同 | |
自动 | 手动 |
3、缓存地方不同 | |
内存 | 磁盘 |
4、存储类型不同 | |
所查数据结果映射成Javabean 的实现类对象地址值 | 所查数据结果映射成Javabean 的实现类对象序列化后的properties 文件 |