招聘网站如何做运营,做海外贸易网站,坪山做网站的公司,大公司需要seo是什么职业背景
除了 RedisTemplate 外#xff0c; 自Spring3.1开始#xff0c;Spring自带了对缓存的支持。我们可以直接使用Spring缓存技术将某些数据放入本机的缓存中#xff1b;Spring缓存技术也可以搭配其他缓存中间件(如Redis等)进行使用#xff0c;将某些数据写入到缓存中间件…背景
除了 RedisTemplate 外 自Spring3.1开始Spring自带了对缓存的支持。我们可以直接使用Spring缓存技术将某些数据放入本机的缓存中Spring缓存技术也可以搭配其他缓存中间件(如Redis等)进行使用将某些数据写入到缓存中间件(缓存中间件可能在其他机器上)中。
常用缓存
EnableCaching: 开启缓存注解功能通常加在启动类上Cacheable: 在方法执行前先查询缓存中是否有数据如果有数据则直接返回缓存数据如果没有缓存数据调用方法并将方法返回值放到缓存中。CachePut: 将方法的返回值放到缓存中。CacheEvit: 将一条或者多条数据从缓存中删除。
使用
1. 添加依赖并配置redis信息
在 pom.xml 中添加依赖
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-cache/artifactId
/dependency在 application.yml 文件中添加依赖
spring:redis:host: 192.168.**.***port: ****password: ****database: 12. 在启动类上添加 EnableCaching 注解 3. 使用缓存注解
package com.itheima.controller;RestController
RequestMapping(/user)
Slf4j
public class UserController {Autowiredprivate UserMapper userMapper;PostMapping// 使用 CachePut 添加缓存数据 key 的生成 userCache::user.id例如 userCache::12CachePut(cacheNames userCache, key #user.id)public User save(RequestBody User user){userMapper.insert(user);return user;}DeleteMapping// 删除指定缓存CacheEvict(cacheNames userCache, key #id)public void deleteById(Long id){userMapper.deleteById(id);}DeleteMapping(/delAll)// 删除所有缓存CacheEvict(cacheNames userCache, allEntries true)public void deleteAll(){userMapper.deleteAll();}GetMapping// key 的生成 userCache::12Cacheable(cacheNames userCache, key #id)public User getById(Long id){User user userMapper.getById(id);return user;}}
4. 结果
这里以 CachePut 注解为例演示结果。 向表中添加数据后可以看到成功将新用户信息添加到了缓存中。 缓存中信息