SpringBoot2 + Vue2 combate real (quatorze) springboot integrado redis para obter cache

1. Adicionar cache

Depois de adicionar o cache redis, o banco de dados não será atualizado o tempo todo, reduzindo a pressão do banco de dados

dependências do pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
Aplicação Springboot
@EnableCaching
EchartsController
 @AuthAccess
    @GetMapping("/file/front/all")
    @Cacheable(value = "files", key = "targetClass + methodName")
    public Result frontAll() {
        return Result.success(fileMapper.selectList(null));
    }

Você também pode personalizar a chave, entre ' '

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

2. Atualize o cache:

fileController

//更新
    @PostMapping("/update")
    //更新缓存
    @CachePut(value = "files",key = "'frontAll'")
    public Result update(@RequestBody Files files) {
        //新增或修改
        fileMapper.updateById(files);
        return success(fileMapper.selectList(null));
    }

3. Exclua o cache

Depois que o banco de dados é excluído, o primeiro cache também é excluído e o banco de dados não será solicitado posteriormente

//删除
    @DeleteMapping("/{id}")
    //清除一条缓存,key为要清空的数据
    @CacheEvict(value = "emp",key = "'frontAll'")
    public Result delete(@PathVariable("id") Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(true);
        fileMapper.updateById(files);
        return success();
    }

4. Integrar redis

pom.xml

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

aplicativo.yml

  redis:
    port: 6379
    host: 127.0.0.1

EchartController

@Resource
    private FileMapper fileMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



@AuthAccess
    @GetMapping("/file/front/all")
    /*@Cacheable(value = "files", key = "targetClass + methodName")*/
    public Result frontAll() {

        //1.从缓存获取数据
        String jsonStr = stringRedisTemplate.opsForValue().get(FILES_KEY);
        List<Files> files;
        //2.取出来的json是空的
        if (StrUtil.isBlank(jsonStr)) {
            //3.从数据库取出数据
            files = fileMapper.selectList(null);
            //4.再去缓存到redis
            stringRedisTemplate.opsForValue().set(FILES_KEY,JSONUtil.toJsonStr(files));
        } else {
            //减轻数据库的压力
            //5.如果有,从redis缓存中获取数据
            files = JSONUtil.toBean(jsonStr, new TypeReference<List<Files>>() {
            }, true);
        }
        return Result.success(files);
    }

Depois de operar a operação de cache de atualização do banco de dados: (usado ao adicionar, excluir e modificar)

O primeiro método: a maneira mais fácil

//最简单的方式
        flushRedis(Constants.FILES_KEY);

excluir cache

FileController

@Autowired
    private StringRedisTemplate stringRedisTemplate;


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




//更新
    @PostMapping("/update")
    //更新缓存
    /*@CachePut(value = "files",key = "'frontAll'")*/
    public Result update(@RequestBody Files files) {
        //新增或修改
        fileMapper.updateById(files);
        flushRedis(Constants.FILES_KEY);
        return success();
    }


 //删除
    @DeleteMapping("/{id}")
    //清除一条缓存,key为要清空的数据
   /* @CacheEvict(value = "emp",key = "'frontAll'")*/
    public Result delete(@PathVariable("id") Integer id) {
        Files files = fileMapper.selectById(id);
        files.setIsDelete(true);
        fileMapper.updateById(files);
        flushRedis(Constants.FILES_KEY);
        return success();
    }

O segundo método:

definir cache

FileController



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

 ① Retire os dados do redis, configure-os após a operação, não há necessidade de consultar o banco de dados e o desempenho é relativamente alto

//从redis取出数据,操作完,再设置,不用查询数据库
        String json = stringRedisTemplate.opsForValue().get(Constants.FILES_KEY);
        List<Files> files1 = JSONUtil.toBean(json, new TypeReference<List<Files>>() {
        },true);
        files1.add(saveFile);
        setCache(Constants.FILES_KEY,JSONUtil.toJsonStr(files1));

② Encontre os dados do banco de dados e defina o cache mais recente

 //从数据库查出数据
        List<Files> files = fileMapper.selectList(null);
        //设置最新的缓存
        setCache(Constants.FILES_KEY, JSONUtil.toJsonStr(files));

Acho que você gosta

Origin blog.csdn.net/m0_64393446/article/details/131636890
Recomendado
Clasificación