实战19 SpringBoot集成 redis缓存

本文详细介绍了如何在SpringBoot项目中集成缓存功能,包括使用SpringBoot内置的缓存以及与Redis的集成,展示了如何配置、使用和管理缓存数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1、springboot 缓存

2、springboot+redis缓存


1、springboot 缓存

添加依赖:

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

开启springboot缓存

 

@AuthAccess
@GetMapping("/file/front/all")
@Cacheable(value = "files",key ="'frontAll'")
public Result frontAll() {
    return Result.success(fileMapper.selectList(null));
}


@CacheEvict(value = "files",key = "'frontAll'")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
    Files files = fileMapper.selectById(id);
    files.setIsDelete(true);
    return Result.success(fileMapper.updateById(files));
}

@CachePut(value = "files",key = "'frontAll'")
@PostMapping("/update")
public Result update(@RequestBody Files files) {
    fileMapper.updateById(files);
    return Result.success(fileMapper.selectList(null));
}

2、springboot+redis缓存

redis依赖

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

redis配置

redis:
  port: 6379  
  host: 127.0.0.1

查询缓存

    @AuthAccess
    @GetMapping("/file/front/all")
//    @Cacheable(value = "files",key ="'frontAll'")
    public Result frontAll() {
        //从缓存获取数据
        String jsonStr = stringRedisTemplate.opsForValue().get(FILES_KEY);
        List<Files> files = new ArrayList<>();
        if (StrUtil.isBlank(jsonStr)){
            files = fileMapper.selectList(null);//从数据库取出数据后,刷缓存
            stringRedisTemplate.opsForValue().set(FILES_KEY,JSONUtil.toJsonStr(files));
        }else {
            //从缓存中查询数据
            files = JSONUtil.toBean(jsonStr, new TypeReference<List<Files>>() {
            },true);
        }
        return Result.success(files);
    }

删除缓存

//删除缓存
private void flushRedis(String key){
    stringRedisTemplate.delete(key);
}

更新缓存

//设置缓存
private void setRedis(String key,String value){
    stringRedisTemplate.opsForValue().set(key,value);
}

List<Files> files = fileMapper.selectList(null);
setRedis(Constants.FILES_KEY, JSONUtil.toJsonStr(files));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值