东莞各类免费建站搜索引擎营销成功的案例
一、基本概念
Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
Spring Cache 提供了一层抽象,底层可以切换不同的缓存实现,例如:
• EHCache
• Caffeine
• Redis
如果要使用Redis的话,记得加上Redis配置,则会自动将Redis作为相对应的缓存
SpringBoot默认使用Simple作为缓存技术,如果要修改,需要在yml中配置spring.cache.type
<!--Redis的配置--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--spring cache--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
二、Spring Cache
名称 | 解释 |
---|---|
Cache | 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等 |
CacheManager | 缓存管理器,管理各种缓存(cache)组件 |
@Cacheable | 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中,不可以使用result关键字 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
@CachePut | 保证方法被调用,又希望结果被缓存。 与@Cacheable区别在于是否每次都调用方法,常用于更新 |
@EnableCaching | 开启缓存注解功能,通常加在启动类上 |
keyGenerator | 缓存数据时key生成策略 |
serialize | 缓存数据时value序列化策略 |
@CacheConfig | 统一配置本类的缓存注解的属性 |
2.1 @CachePut
//如果使用Spring Cache 缓存数据//key生成:userCache::abc//set a:b:c:d itheima ---> key:a:b:c:d values:itheima//key对应的是 #参数的主键值【动态计算key值】,结果值都是一样的@CachePut(cacheNames = "userCache",key = "#user.id")//对象导航//@CachePut(cacheNames = "userCache",key = "#result.id")//p0:表示第一个参数//@CachePut(cacheNames = "userCache",key = "#p0.id")//a0:表示第一个参数//@CachePut(cacheNames = "userCache",key = "#a0.id")@PostMappingpublic User save(@RequestBody User user){userMapper.insert(user);return user;}
2.2 @ EnableCaching
@Slf4j
@SpringBootApplication
@EnableCaching//开启缓存注解功能
public class CacheDemoApplication {public static void main(String[] args) {SpringApplication.run(CacheDemoApplication.class,args);log.info("项目启动成功...");}
}
2.3 @ Cacheable
/*** 注意点:* Cacheable与CachePut 不一样: Cacheable的key中不能使用#result.id* 1. Spring Cache底层是代理对象,使用时先在redis中查询是否有数据,如果有则直接调出,不用使用sql查询* 2. 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中,不可以使用result关键字* @param id* @return*/@Cacheable(cacheNames = "userCache",key = "#id")@GetMappingpublic User getById(Long id){User user = userMapper.getById(id);return user;}
2.4 @ CacheEvict
/*** @CacheEvict:将一条或多条数据从缓存中删除* @param id*/@DeleteMapping@CacheEvict(cacheNames = "userCache",key = "#id")public void deleteById(Long id){userMapper.deleteById(id);}
参考:史上最全的Spring Boot Cache使用与整合_我俗人的博客-CSDN博客