Java 缓存简介

本贴最后更新于 727 天前,其中的信息可能已经东海扬尘

缓存(Cache)简介

为什么要使用缓存

image.png

缓存在各种Web形态项目中有广泛应用

image.png

Java后端开发中有哪些缓存

本地缓存

分布式缓存

主要概念

Spring缓存框架

概述

声明式缓存

编程式缓存

SpringBoot中使用缓存

概述

SpringBoot中使用Redis

使用方式

  1. 在pom.xml中添加spring-boot-starter-cache、spring-boot-starter-data-redis依赖,以及commons-pool2依赖,这个是Lettuce依赖
  2. 在启动类添加@EnableCaching注解
  3. 在application.properties中添加配置:spring.cache.type=redis,并添加redis相关的配置,包括连接的服务器ip、端口、过期时间等,具体见示例
  4. 在程序中使用声明式缓存、编程式缓存方式进行操作

声明式使用

编程式使用

public ResponseData<List<GradeOutputDto>> queryAll() {
        ResponseData<List<GradeOutputDto>> responseData = new ResponseData<>();
        try {
            //返回DTO引用
            List<GradeOutputDto> gradeOutputDtos = null;
            //【缓存】根据缓存Key获取缓存,如果存在,从缓存中获取数据
            if(redisTemplate.hasKey(CACHE_KEY_FOR_ALL_GRADE) == true){
                //根据Key获取缓存信息
                gradeOutputDtos = (List <GradeOutputDto>)redisTemplate.opsForList().range(CACHE_KEY_FOR_ALL_GRADE,0,redisTemplate.opsForList().size(CACHE_KEY_FOR_ALL_GRADE));
            }
            //如果不存在,则从数据库中获取
            if(gradeOutputDtos == null) {
                //查询
                List<GradeEntity> gradeEntities = this.list();
                //Entity转Dto
                gradeOutputDtos = gradeEntities.stream().map(s->modelMapper.map(s,GradeOutputDto.class)).collect(Collectors.toList());

                //【缓存】从数据库获取后,将数据缓存到Redis
                redisTemplate.opsForList().leftPushAll(CACHE_KEY_FOR_ALL_GRADE,gradeOutputDtos);
                //【缓存】设置过期时间,使用动态过期时间
                redisTemplate.expire(CACHE_KEY_FOR_ALL_GRADE,redisTemplateUtil.getExpire(CACHE_NAME));
            }

            responseData = ResponseData.success(gradeOutputDtos);
        } catch (Exception ex) {
            responseData = ResponseData.failure(ex.getMessage());
            ex.printStackTrace();
        }

        return responseData;
    }
回帖
请输入回帖内容 ...