springboot缓存

1. 认识缓存  一级缓存

- 缓存是一种介于数据永久存储介质与数据应用之间的数据临时存储介质

- 使用缓存可以有效的减少低速数据读取过程的次数,提高系统性能 

 

@Service
public class BookServiceImplCache implements BookService {
    @Autowired
    private BookDao bookDao;

    private HashMap<Integer,Book> cache =new HashMap();
@Override
public Book getById(Integer id) {
    Book book =cache.get(id);
    if(book ==null){
        //如果boo的id在缓存中不存在,就去数据库中读取,并将读取结果写在缓存中
        //如果在缓存中,则直接去读取缓存中数据
        System.out.println("打印查看map中是否有查询id 的数据------"+cache.get(id));
        Book queryBookFromSQL =bookDao.getById(id);
        cache.put(id,queryBookFromSQL);
        System.out.println("打印查看map中是否有查询id 的数据------"+cache.get(id));
        System.out.println("当前缓存中的所有数据");
        System.out.println("通过Map.keySet遍历key和value:");
        for (Integer key : cache.keySet()) {
            System.out.println("key= "+ key + " and value= " + cache.get(key));
        }

        return queryBookFromSQL;
    }
    return cache.get(id);
}

第一次执行的结果------缓存中没有数据,会从数据库去拿数据==>  Preparing: select * from tbl_book where id = ?,

也会将读取的数据,放入到map中去

打印查看map中是否有查询id 的数据------null
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@118f4b27] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5b87f91c] will not be managed by Spring
==>  Preparing: select * from tbl_book where id = ?
==> Parameters: 122229(Integer)
<==    Columns: id, type, name, description
<==        Row: 122229, for better tomorrow, from today, 我是行动上的巨人
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@118f4b27]
打印查看map中是否有查询id 的数据------Book(id=122229, type=for better tomorrow, name=from today, description=我是行动上的巨人)

 

第二次执行的结果

---控制台没有去数据库读取数据,证明此次是从map中拿取的数据 

2. 二级缓存

- 缓存不仅可以用于提高永久性存储介质的数据读取效率,还可以提供临时的数据存储空间

3 . 使用SpringBoot提供的缓存技术

- 缓存的使用

  -  1. 启用缓存

  -   2. 设置进入缓存的数据

  -  3  设置读取缓存的数据

导入坐标

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

 开启缓存,

在application上添加 

@EnableCaching
@Override
@Cacheable(value = "cacheSpace",key="#id")
public Book getById(Integer id) {
    return bookDao.getById(id);
}

______________________________________

一个小插曲报错

启动Redis报错 java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload

原因: 实体类是一个对象
在redis序列化的时候采用的是 gdk序列化

解决办法
类implements Serializable
不然redis不知道此类是可以被序列化的

 

______________________________________

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>