1,SpringCache
1.1 概述
Spring Cache 使用方法与 Spring 对事务管理的配置相似。Spring Cache 的核心就是对某个方法
进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的方式存放到
缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指定的结果进行返
回
1.2 常用注解:
@Cacheable-------使用这个注解的方法在执行后会缓存其返回结果。
@CacheEvict--------使用这个注解的方法在其执行前或执行后移除SpringCache中的某些元素。
2,活动信息的缓存
2.1 代码生成
(1)使用代码生成器生成活动微服务代码 tensquare_gathering
(2)拷贝到当前工程,并在父工程引入。
(3)修改 Application 类名称为 GatheringApplication
(4)修改 application.yml 中的端口为 9005 ,url 为
jdbc:mysql://192.168.184.134:3306/tensquare_gathering?characterEncoding=UTF8
(5)进行浏览器测试
2.2 开启缓存支持
在启动类中GatheringApplication 添加@EnableCaching 开启缓存支持
package com.tensquare.gathering;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import util.IdWorker;
@SpringBootApplication
@EnableCaching //开启SpringCache
public class GatheringApplication {
public static void main(String[] args) {
SpringApplication.run(GatheringApplication.class, args);
}
@Bean
public IdWorker idWorkker(){
return new IdWorker(1, 1);
}
}
2.3 为方法添加缓存注解
在 GatheringService 的 findById 方法添加缓存注解,这样当此方法第一次运行,在
缓存中没有找到对应的 value 和 key,则将查询结果放入缓存。
/**
* 根据ID查询实体
* @param id
* @return
*/
/**
* value: 缓存的别名,这个value值在删除缓存时使用
* key: 给该返回值对象指定一个key值 (通常取方法的参数值 # )
*/
@Cacheable(value = "gathering",key = "#id")
public Gathering findById(String id) {
return gatheringDao.findById(id).get();
}
2.4 删改时更新缓存
当我们对数据进行删改的时候,需要更新缓存。其实更新缓存也就是清除缓存,因
为清除缓存后,用户再次调用查询方法无法提取缓存会重新查找数据库中的记录并放入
缓存。
在 GatheringService 的 update、deleteById 方法上添加清除缓存的注解
/**
* 修改
* @param gathering
*/
/**
* value: 缓存的别名
* key: 需要删除的缓存对象的key
*/
@CacheEvict(value = "gathering",key = "#gathering.id" )
public void update(Gathering gathering) {
gatheringDao.save(gathering);
}
/**
* 删除
* @param id
*/
@CacheEvict(value = "gathering",key = "#id" )
public void deleteById(String id) {
gatheringDao.deleteById(id);
}
3,SpringCach和 Spring Data Redis区别**
1)代码实现角度
SpringCache只需要在方法上面加上@Cacable @CacacheEvict就可以实现缓存,比较简单!
Spring Data Redis需要修改原来的方法,加入逻辑才可以实现,相对复杂点!
2) 存储方式角度
Spring Cache缓存在应用内存中,应用停止,缓存丢失啦!
Spring Data Redis缓存在Redis服务器,Redis可以持久化,缓存不会轻易丢失!
3)分布式角度
Spirng Cache只支持单机应用缓存,不支持分布式
SpringData Redis可以在分布式环境下使用
4)过期时间设置
SpringCache不支持过期时间设置
SpringDataRedis支持设置
结论:
如果你的项目的缓存数据,不需要在分布环境下使用,且不需要持久化,可以使用SpringCache
如果你的项目的缓存数据,需要分布式,或者需要持久态,都需要使用SpringDataRedis