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

【项目】小帽外卖(十二)

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

【项目】小帽外卖(十二)

小帽外卖 第十二章 缓存优化
  • 问题说明
一、环境搭建 1. maven坐标


	org.springframework.boot
	spring-boot-starter-data-redis

2. 配置文件


spring
	redis:
		host: 172.17.2.94
		port: 6379
		password: root@123456
		database: 0
3. 配置类
// 在项目中加入配置类RedisConfig:
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        //默认的Key序列化器为:JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}
二、缓存短信验证码 1. 实现思路
  • 前面我们已经实现了移动端手机验证码登录,随机生成的验证码我们是保存在HttpSession中的。
  • 现在需要改造为将验证码缓存在Redis中,具体的实现思路如下:
    1、在服务端UserController中注入RedisTemplate对象,用于操作Redis
    2、在服务端UserController的sendMsg方法中,将随机生成的验证码缓存到Redis中,并设置有效期为5分钟
    3、在服务端UserController的login方法中,从Redis中获取缓存的验证码,如果登录成功则删除Redis中的验证码
2. 代码改造
  • 在UserController中注入RedisTemplate对象,用于操作Redis
@Autowired
private RedisTemplate redisTemplate;
  • 在UserController的sendMsg方法中,将生成的验证码保存到Redis
// 将生成的验证码缓存到Redis中,并且设置有效期为5分钟
redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
  • 在UserController的login方法中,从Redis中获取生成的验证码,如果登录成功则删除Redis中缓存的验证码
// 从Redis中获取缓存的验证码
Object codeInSession = redisTemplate.opsForValue().get(phone);

// 如果用户登录成功,删除Redis中缓存的验证码
redisTemplate.delete(phone);
return R.success(user);
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session) {
        // 获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)) {
            // 生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            // 调用阿里云提供的短信服务API完成发送短信
            // SMSUtils.sendMessage("小帽外卖", "", phone, code);
            // 需要将生成的验证码保存到Session
            // session.setAttribute(phone, code);

            // 将生成的验证码缓存到Redis中,并且设置有效期为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.success("手机验证码短信发送成功");
        }

        return R.error("短信发送失败");
    }

    
    @PostMapping("/login")
    public R sendMsg(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
        // 获取手机号
        String phone = map.get("phone").toString();
        // 获取验证码
        String code = map.get("code").toString();
        // 从Session中获取保存的验证码
        // Object codeInSession = session.getAttribute(phone);
        // 从Redis中获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        // 进行验证码的比对(页面提交的验证码和Session中保存的验证码比对)
        if(codeInSession != null && codeInSession.equals(code)) {
            // 如果能够比对成功,说明登录成功
            // 判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
            LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if(user == null) {
                // 判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            // 如果用户登录成功,删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败");
    }
}
三、缓存菜品数据 1. 实现思路
  • 前面我们已经实现了移动端菜品查看功能,对应的服务端方法为DishController的list方法,此方法会根据前端提交的查询条件进行数据库查询操作。在高并发的情况下,频繁查询数据库会导致系统性能下降,服务端响应时间增长。现在需要对此方法进行缓存优化,提高系统的性能。
  • 具体的实现思路如下:
    1、改造DishController的list方法,先从Redis中获取菜品数据,如果有则直接返回,无需查询数据库;如果没有则查询数据库,并将查询到的菜品数据放入Redis。
    2、改造DishController的save和update方法,加入清理缓存的逻辑
  • 注意事项:
    • 在使用缓存过程中,要注意保证数据库中的数据和缓存中的数据一致,如果数据库中的数据发生变化,需要及时清理缓存数据。
2. 代码改造
  • 在DishController中注入RedisTemplate对象,用于操作Redis
@Autowired
private RedisTemplate redisTemplate;
  • 改造DishController的list方法
@GetMapping("/list")
public R> list(Dish dish) {
        List dishDtoList = null;
        // 动态构造key
        String key = "dish" + dish.getCategoryId() + "_" + dish.getStatus();    // dish_1234757727727_1
        // 先从redis中获取缓存数据
        dishDtoList= (List) redisTemplate.opsForValue().get(key);

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

// 如果不存在,需要查询数据库,将查询到的菜品数据缓存到Redis
redisTemplate.opsForValue().set(key, dishDtoList,60, TimeUnit.MINUTES);
return R.success(dishDtoList);
  • 改造DishController的update方法
@PutMapping
public R update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        // 清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
}
  • 改造DishController的save方法
@PostMapping
public R save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        // 清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
}
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        // 清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }
    
    
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        // 清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    
    @GetMapping("/list")
    public R> list(Dish dish) {
        List dishDtoList = null;
        // 动态构造key
        String key = "dish" + dish.getCategoryId() + "_" + dish.getStatus();    // dish_1234757727727_1
        // 先从redis中获取缓存数据
        dishDtoList= (List) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null) {
            // 如果存在,直接返回,无需查询数据库
            return R.success(dishDtoList);
        }
        // 构造查询条件
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 添加条件,查询状态为1(起售状态)的菜品
        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();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId(); // 分类id
            // 根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            // 当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishId);
            List dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        // 如果不存在,需要查询数据库,将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key, dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
四、Spring Cache 1. Spring Cache 介绍
  • Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
  • Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。
  • CacheManager是Spring提供的各种缓存技术抽象接口。
  • 针对不同的缓存技术需要实现不同的CacheManager:
2. Spring Cache 常用注解

  • 在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。
  • 例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。
3. Spring Cache 使用方式
  • 在Spring Boot项目中使用Spring Cache的操作步骤(使用redis缓存技术):
    1、导入maven坐标
    spring-boot-starter-data-redis、spring-boot-starter-cache
    2、配置application.yml

    3、在启动类上加入@EnableCaching注解,开启缓存注解功能
    4、在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作
4. Spring Cache 上下文数据

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private UserService userService;

    
    @CachePut(value = "userCache",key = "#user.id")
    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }

    
    @CacheEvict(value = "userCache",key = "#p0")
    //@CacheEvict(value = "userCache",key = "#root.args[0]")
    //@CacheEvict(value = "userCache",key = "#id")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }

    //@CacheEvict(value = "userCache",key = "#p0.id")
    //@CacheEvict(value = "userCache",key = "#user.id")
    //@CacheEvict(value = "userCache",key = "#root.args[0].id")
    @CacheEvict(value = "userCache",key = "#result.id")
    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }

    
    @Cacheable(value = "userCache",key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

    @Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")
    @GetMapping("/list")
    public List list(User user){
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null,User::getId,user.getId());
        queryWrapper.eq(user.getName() != null,User::getName,user.getName());
        List list = userService.list(queryWrapper);
        return list;
    }
}
@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("项目启动成功...");
    }
}
五、缓存套餐数据 1. 实现思路
  • 前面我们已经实现了移动端套餐查看功能,对应的服务端方法为SetmealController的list方法,此方法会根据前端提交的查询条件进行数据库查询操作。在高并发的情况下,频繁查询数据库会导致系统性能下降,服务端响应时间增长。现在需要对此方法进行缓存优化,提高系统的性能。
  • 具体的实现思路如下:
    1、导入Spring Cache和Redis相关maven坐标
    2、在application.yml中配置缓存数据的过期时间
    3、在启动类上加入@EnableCaching注解,开启缓存注解功能
    4、在SetmealController的list方法上加入@Cacheable注解
    5、在SetmealController的save和delete方法上加入CacheEvict注解
2. 代码改造


	org.springframework.boot
	spring-boot-starter-cache

# 在application.yml中配置缓存数据过期时间:
spring:
  cache:
    redis:
      time-to-live: 1800000 # 设置缓存数据过期时间
// 在启动类上加入@EnableCaching注解:
@Slf4j
@SpringBootApplication
@ServletComponentScan
@EnableTransactionManagement
@EnableCaching // 开启Spring Cache注解方式缓存功能
public class LemonApplication {
    public static void main(String[] args) {
        SpringApplication.run(LemonApplication.class, args);
        log.info("项目启动成功...");
    }
}
// 在SetmealController的list方法上加入@Cacheable注解
// 在SetmealController的save和delete方法上加入@CacheEvict注解
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息:{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R delete(@RequestParam List ids) {
        log.info("ids:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R> list(Setmeal setmeal) {
        LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List list = setmealService.list(queryWrapper);
        return R.success(list);
    }
}

// 在返回结果类R需要实现序列化接口
@Data
public class R implements Serializable {

    private Integer code; //编码:1成功,0和其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    private Map map = new HashMap(); //动态数据

    public static  R success(T object) {
        R r = new R();
        r.data = object;
        r.code = 1;
        return r;
    }

    public static  R error(String msg) {
        R r = new R();
        r.msg = msg;
        r.code = 0;
        return r;
    }

    public R add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

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

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

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