@EnableCache:开启缓存注解功能
@Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据,若没有数据,调用方法并将方法返回值放到缓存中
unless:当满足条件则排除
@CachePut:将方法的返回值放到缓存中
@CacheEvict:将一条或多条数据从缓存中删除
不同的缓存技术实现不同的CacheManager
@EnCacheCacheManager:encahe作为缓存技术
@GuavaCacheManager:使用谷歌的GuavaCache
@RedisCacheManager:redis作为缓存技术
springcache整合Redis
1.pom.xml添加坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.在.yml配置文件中添加redis过期时间
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/database?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: password
redis:
host: localhost
port: 6379
password: password
database: 0
cache:
redis:
time-to-live: 1800000 #配置缓存过期时间
3.在启动类中添加@EnableCache注解
package org.example.reggie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Hello world!
*
*/
@Slf4j
@SpringBootApplication
@ServletComponentScan
@EnableTransactionManagement
@EnableCaching
public class ReggieApplication
{
public static void main( String[] args )
{
SpringApplication.run(ReggieApplication.class, args);
log.info( "项目启动成功!" );
}
}
在需要获取数据的方法上加上注解 @Cacheable(value = "setmealCache" ,key="#setmeal.categoryId+'_'+#setmeal.status")在删除、保存、更新方法上添加上注解@CacheEvict:
@CacheEvict(value = "setmealCache" ,allEntries = true)//allentries表示将setmealCache的所有数据都删掉,默认是false
如果返回实体是R,需要在实体类加上序列化接口
public class R<T> implements Serializable {