栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot-redis缓存数据信息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot-redis缓存数据信息

springboot-redis缓存数据信息

(新手笔记,狂神搬运工)
**本篇依据狂神瑞吉外卖项目缓存短信,菜品数据部分进行记录

狂神说Java

springboot-redis缓存数据信息
  • springboot-redis缓存数据信息
  • redis配置
    • 依赖导入
  • 缓存短信验证码
  • 缓存菜品数据
    • 缓存菜品数据
    • 清理缓存

redis配置 依赖导入
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
       
        
            org.apache.commons
            commons-pool2
        

yaml配置redis

server:
  port: 8080
spring:
  redis:
    database: 0  #操作0号数据库
    host: 127.0.0.1
    port: 6379
    password: '123456'
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: 100ms

##rediscofig配置(主要是为了redis图形化界面便于查看数据)

package com.itheima.reggie.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;



@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate redisTemplate = new RedisTemplate<>();

        //默认的Key序列化器为:JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        redisTemplate.setConnectionFactory(connectionFactory);

        return redisTemplate;
    }

}

缓存短信验证码

在未优化的项目中,验证码存储在session中,有效期(30min),我们需要将其缓存在redis中:

//先注入redistenmplate
    @Autowired
    private RedisTemplate redisTemplate;

//在发送验证码的方法中修改,将验证码存在redis中
//设置有效期为5分钟,将phone设置为key
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

//在登陆方法中
//从redis中获取缓存的验证码
Object codeInSession=redisTemplate.opsForValue().get(phone);
//用户登陆成功,删除redis中缓存的验证码
   redisTemplate.delete(phone);

缓存菜品数据 缓存菜品数据

在移动端,用户查询某个菜品分类时都要查询数据库,造成频繁访问,极大的降低了性能,所以需要将菜品数据存放在缓存中,避免频繁访问数据库。
思路:先从redis中获取菜品数据,如果有则直接返回,不需要查询数据库,如果没有则查询数据库,并将查询到的数据放入redis。
改造菜品新增和更新方法,加入清理缓存逻辑。
(缓存使用中要注意保证数据库中的数据和缓存中的数据的一致性,数据库中的数据发生变化时,要及时清理缓存数据)

//在dishcontroller中先注入redistemplate
    @Autowired
    private RedisTemplate redisTemplate;


 //在获取菜品数据方法中添加缓存
   @GetMapping("/list")
    public R> list(Dish dish)
    {
        List dishDtoList=null;
        //动态构造key
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        //先从redis中获取缓存数据
        dishDtoList= (List) redisTemplate.opsForValue().get(key);

        if(dishDtoList!=null)
        {
            //如果存在直接返回,不需要查询数据库
            return R.success(dishDtoList);

        }


        //如果不存在,需要查询数据库,查询出的菜品数据缓存到redis

        //构造查询条件
        LambdaQueryWrapper queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1 );
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List list = dishService.list(queryWrapper);
           dishDtoList=list.stream().map((item)->{
            DishDto dishDto=new DishDto();
            //使用对象拷贝给dishdto的普通属性赋值
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null)
            {
                String name1 = category.getName();
                dishDto.setCategoryName(name1);
            }
            Long dishId = item.getId();//菜品id
            LambdaQueryWrapper lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

           //缓存到redis
           redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }


清理缓存

错误分析:
当增加一个菜品后,再次查询菜品会发现看不到新增的菜品,因为在新增菜品前缓存没有清理,新增菜品后,再次查询数据并不会查询数据库,而是查询旧的缓存,导致出错。修改菜品同样也会出现这种错误。
在清理缓存时可以清理掉全部缓存(数据较少时),也可以精确清理。
修改菜品缓存清理:

   @PutMapping
    public R update(@RequestBody DishDto dishDto)//前端传回的json数据由requestbody反序列化到实体对象中
    {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //清理某个分类下面的菜品缓存,构造key
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }

新增菜品的缓存修改同理

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号