1.在pom中引入redis相关依赖
org.springframework.boot
spring-boot-starter-data-redis
2.进行yml配置
spring:
redis:
host: xxx.xxx.xxx.xxx #IP地址
port: 6379 #端口
password: xxx #密码
database: 0 #数据库 默认0
ssl: false #是否开启ssl安全访问
3.代码案例
//LiquidityVO是我定义的对象,这里可以换成你自己的 public ListmobilityTrends(RequestParameterTO requestParameterTO) { //获取ObjectMapper实例对象用于JSON格式数据解析 ObjectMapper mapper = new ObjectMapper(); //从redis中通过key获取对应的值 String listJSON = (String) redisTemplate.opsForValue().get(requestParameterTO.getQuery()); //判断该值是否为空 if (StringUtils.isNotEmpty(listJSON)) { List list = null; try { //进行JSON格式解析,解析的数据类型是一个集合泛型是我自定义的对象 list = mapper.readValue(listJSON, new TypeReference >() { }); } catch (IOException e) { throw new RuntimeException(e); } //直接返回数据 return R.data(list); } else { //因为redis中没有key相对应的数据,假设该集合是从数据库中查询所得 List
list = new ArrayList<>(); String string = null; try { //通过writeValueAsString方法进行JSON格式转换 string = mapper.writeValueAsString(list); } catch (JsonProcessingException e) { throw new RuntimeException(e); } //把转换之后的数据存入到redis中,key可以自定义,43200000是缓存失效时间单位是毫秒 redisTemplate.opsForValue().set("key", string, 43200000, TimeUnit.SECONDS); //进行数据返回 return R.data(list); }



