【java】【项目实战】[外卖九]项目优化(缓存)

目录

一、问题说明

二、环境搭建

2.1 Git管理代码

2.1.1 创建本地仓库

2.1.2 创建远程仓库

2.1.3 创建分支--》推送到远程仓库

2.2 maven坐标

2.3 配置文件application.yml

2.4 配置类RedisConfig

三、缓存短信验证码

3.1 实现思路

3.2 代码改造

3.2.1 UserController

3.3 功能测试

四、缓存菜品数据

4.1 实现思路

4.2 代码改造

4.2.1 第一步改造DishController 中list方法

4.2.2 第三步改造DishController中的save和update方法 

4.3 功能测试

五、Spring Cache

5.1 Spring Cache介绍

5.2 Spring Cache常用注解

5.3 Spring Cache使用方式

 5.3.1 pom

六、缓存套餐数据

6.1 实现思路

6.2 代码改造

 6.2.1 pom 坐标

6.2.2 application.yml配置缓存数据过期时间

6.2.3 开启缓存注解功能 ReggieApplication

 6.2.4  R实现 Serializable 接口

 6.2.5 在SetmealController的list方法加入@Cacheable注解

6.2.6 在SetmealController的delete方法加入@CacheEvict注解

6.2.7 在SetmealController的save方法加入@CacheEvict注解

6.3 功能测试


前言:使用缓存进行项目优化

一、问题说明

二、环境搭建

2.1 Git管理代码

2.1.1 创建本地仓库

2.1.2 创建远程仓库

略。。后续都省略

2.1.3 创建分支--》推送到远程仓库

2.2 maven坐标

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

2.3 配置文件application.yml

server:port: 8080
spring:application:# 应用名称 可选name: reggie_take_out_spuerdatasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rotpassword: ruredis:host: 127.0.0.1port: 6379password: 123database: 0
mybatis-plus:configuration:#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射map-underscore-to-camel-case: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:id-type: ASSIGN_ID
# 文件上传目录
reggie:path: D:\images\

2.4 配置类RedisConfig

package com.runa.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 {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();//默认的Key序列化器为:JdkSerializationRedisSerializerredisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setConnectionFactory(connectionFactory);return redisTemplate;}
}

三、缓存短信验证码

3.1 实现思路

3.2 代码改造

3.2.1 UserController

package com.runa.reggie.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.runa.reggie.common.R;
import com.runa.reggie.entity.User;
import com.runa.reggie.service.UserService;
import com.runa.reggie.utils.SMSUtils;
import com.runa.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {@Autowiredprivate UserService userService;@Autowiredprivate RedisTemplate redisTemplate;/*** 发送手机短信验证码* @param user* @return*/@PostMapping("/sendMsg")public R<String> 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("短信发送失败");}/*** 移动端用户登录* @param map* @param session* @return*/@PostMapping("/login")public R<User> login(@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<User> 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("登录失败");}}

3.3 功能测试

启动后端服务、启动redis

http://localhost:8080/front/page/login.html

四、缓存菜品数据

4.1 实现思路

4.2 代码改造

4.2.1 第一步改造DishController 中list方法

package com.runa.reggie.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.dto.DishDto;
import com.runa.reggie.entity.Category;
import com.runa.reggie.entity.Dish;
import com.runa.reggie.entity.DishFlavor;
import com.runa.reggie.service.CategoryService;
import com.runa.reggie.service.DishFlavorService;
import com.runa.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;/*** 菜品管理*/
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {@Autowiredprivate DishService dishService;@Autowiredprivate DishFlavorService dishFlavorService;@Autowiredprivate CategoryService categoryService;@Autowiredprivate RedisTemplate redisTemplate;/*** 新增菜品* @param dishDto* @return*/@PostMappingpublic R<String> save(@RequestBody DishDto dishDto){log.info(dishDto.toString());dishService.saveWithFlavor(dishDto);return R.success("新增菜品成功");}@GetMapping("/page")public R<Page> page(int page, int pageSize, String name){// 构造分页构造器对象Page<Dish> pageInfo = new Page<>(page, pageSize);Page<DishDto> dishDtoPage = new Page<>();//条件构造器LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();// 添加过滤条件queryWrapper.like(name != null,Dish::getName,name);// 添加排序条件queryWrapper.orderByDesc(Dish::getUpdateTime);//执行分页查询dishService.page(pageInfo,queryWrapper);// 对象拷贝BeanUtils.copyProperties(pageInfo, dishDtoPage,"records");List<Dish> records = pageInfo.getRecords();List<DishDto> list = records.stream().map((item) -> {DishDto dishDto = new DishDto();BeanUtils.copyProperties(item,dishDto);Long categoryId = item.getCategoryId();// 分类idCategory category = categoryService.getById(categoryId);String categoryName = category.getName();dishDto.setCategoryName(categoryName);return dishDto;}).collect(Collectors.toList());dishDtoPage.setRecords(list);return R.success(dishDtoPage);}/*** 根据ID 查询菜品和对应口味信息 回显* @param id* @return*/@GetMapping("/{id}")public R<DishDto> get(@PathVariable Long id){log.info("要查询显示的菜品信息是:{}",id);DishDto dishDto = dishService.getByIdWithFlavor(id);return R.success(dishDto);}/*** 修改菜品* @param dishDto* @return*/@PutMappingpublic R<String> update(@RequestBody DishDto dishDto){log.info(dishDto.toString());dishService.updateWithFlavor(dishDto);return R.success("修改菜品成功");}//    /**
//     * 根据条件查询对于菜品数据
//     * @param dish
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//
//        // 构造查询条件
//        LambdaQueryWrapper<Dish> 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<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
//}/*** 根据条件查询对于菜品数据* @param dish* @return*/@GetMapping("/list")public R<List<DishDto>> list(Dish dish){List<DishDto> dishDtoList = null;// 动态构造keyString key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();// 先从redis获取缓存数据dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);if(dishDtoList != null){// 1 如果存在,直接返回,无需查询数据库return R.success(dishDtoList);}// 2 如果不存在,需要查询数据库,// 构造查询条件LambdaQueryWrapper<Dish> 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<Dish> 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);}// 当前菜品的idLong dishId = item.getId();LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);dishDto.setFlavors(dishFlavorList);return dishDto;}).collect(Collectors.toList());// 2-1 不存在,将查询到的菜品数据缓存到redisredisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);return R.success(dishDtoList);}
}

4.2.2 第三步改造DishController中的save和update方法 

package com.runa.reggie.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.dto.DishDto;
import com.runa.reggie.entity.Category;
import com.runa.reggie.entity.Dish;
import com.runa.reggie.entity.DishFlavor;
import com.runa.reggie.service.CategoryService;
import com.runa.reggie.service.DishFlavorService;
import com.runa.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;/*** 菜品管理*/
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {@Autowiredprivate DishService dishService;@Autowiredprivate DishFlavorService dishFlavorService;@Autowiredprivate CategoryService categoryService;@Autowiredprivate RedisTemplate redisTemplate;/*** 新增菜品* @param dishDto* @return*/@PostMappingpublic R<String> save(@RequestBody DishDto dishDto){log.info(dishDto.toString());dishService.saveWithFlavor(dishDto);// 清理Redis所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");// 清理Redis某个分类下的菜品的缓存数据// 动态构造keyString key = "dish_" + dishDto.getCategoryId() + "_1";redisTemplate.delete(key);return R.success("新增菜品成功");}@GetMapping("/page")public R<Page> page(int page, int pageSize, String name){// 构造分页构造器对象Page<Dish> pageInfo = new Page<>(page, pageSize);Page<DishDto> dishDtoPage = new Page<>();//条件构造器LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();// 添加过滤条件queryWrapper.like(name != null,Dish::getName,name);// 添加排序条件queryWrapper.orderByDesc(Dish::getUpdateTime);//执行分页查询dishService.page(pageInfo,queryWrapper);// 对象拷贝BeanUtils.copyProperties(pageInfo, dishDtoPage,"records");List<Dish> records = pageInfo.getRecords();List<DishDto> list = records.stream().map((item) -> {DishDto dishDto = new DishDto();BeanUtils.copyProperties(item,dishDto);Long categoryId = item.getCategoryId();// 分类idCategory category = categoryService.getById(categoryId);String categoryName = category.getName();dishDto.setCategoryName(categoryName);return dishDto;}).collect(Collectors.toList());dishDtoPage.setRecords(list);return R.success(dishDtoPage);}/*** 根据ID 查询菜品和对应口味信息 回显* @param id* @return*/@GetMapping("/{id}")public R<DishDto> get(@PathVariable Long id){log.info("要查询显示的菜品信息是:{}",id);DishDto dishDto = dishService.getByIdWithFlavor(id);return R.success(dishDto);}/*** 修改菜品* @param dishDto* @return*/@PutMappingpublic R<String> update(@RequestBody DishDto dishDto){log.info(dishDto.toString());dishService.updateWithFlavor(dishDto);// 清理Redis所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");// 清理Redis某个分类下的菜品的缓存数据// 动态构造keyString key = "dish_" + dishDto.getCategoryId() + "_1";redisTemplate.delete(key);return R.success("修改菜品成功");}//    /**
//     * 根据条件查询对于菜品数据
//     * @param dish
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//
//        // 构造查询条件
//        LambdaQueryWrapper<Dish> 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<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
//}/*** 根据条件查询对于菜品数据* @param dish* @return*/@GetMapping("/list")public R<List<DishDto>> list(Dish dish){List<DishDto> dishDtoList = null;// 动态构造keyString key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();// 先从redis获取缓存数据dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);if(dishDtoList != null){// 1 如果存在,直接返回,无需查询数据库return R.success(dishDtoList);}// 2 如果不存在,需要查询数据库,// 构造查询条件LambdaQueryWrapper<Dish> 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<Dish> 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);}// 当前菜品的idLong dishId = item.getId();LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);dishDto.setFlavors(dishFlavorList);return dishDto;}).collect(Collectors.toList());// 2-1 不存在,将查询到的菜品数据缓存到redisredisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);return R.success(dishDtoList);}
}

4.3 功能测试

http://localhost:8080/front/page/login.htmlhttp://localhost:8080/backend/index.html

 

五、Spring Cache

5.1 Spring Cache介绍

5.2 Spring Cache常用注解

5.3 Spring Cache使用方式

 5.3.1 pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.runa</groupId><artifactId>reggie_take_out_spuer</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version><relativePath/> <!-- lookup parent from repository --></parent><name>reggie_take_out_spuer</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><!--阿里云短信服务--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.16</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>2.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><scope>compile</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.23</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><!--redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--  spring Cache         --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.4.5</version></plugin></plugins></build>
</project>

六、缓存套餐数据

6.1 实现思路

6.2 代码改造

 6.2.1 pom 坐标

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.runa</groupId><artifactId>reggie_take_out_spuer</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version><relativePath/> <!-- lookup parent from repository --></parent><name>reggie_take_out_spuer</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><dependencies><!--阿里云短信服务--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.5.16</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>2.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><scope>compile</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.23</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><!--redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--  spring Cache         --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.4.5</version></plugin></plugins></build>
</project>

6.2.2 application.yml配置缓存数据过期时间

server:port: 8080
spring:application:# 应用名称 可选name: reggie_take_out_spuerdatasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: runa#2050redis:host: 127.0.0.1port: 6379password: 123456database: 0cache:redis:time-to-live: 1800000  # 设置缓存数据的过期时间
mybatis-plus:configuration:#在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射map-underscore-to-camel-case: truelog-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:db-config:id-type: ASSIGN_ID
# 文件上传目录
reggie:path: D:\images\

6.2.3 开启缓存注解功能 ReggieApplication

 

package com.runa.reggie;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;@Slf4j
@SpringBootApplication
@ServletComponentScan
@EnableTransactionManagement
@EnableCaching  // 开启spring Cache注解方式的缓存功能
public class ReggieApplication {public static void main(String[] args) {SpringApplication.run(ReggieApplication.class,args);log.info("项目启动成功~~~");}
}

 6.2.4  R实现 Serializable 接口

package com.runa.reggie.common;import lombok.Data;import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;/*** 通用返回结果,服务端响应的数据最终都会封装成此对象* @param <T>*/
@Data
public class R<T> implements Serializable {private Integer code; //编码:1成功,0和其它数字为失败private String msg; //错误信息private T data; //数据private Map map = new HashMap(); //动态数据public static <T> R<T> success(T object) {R<T> r = new R<T>();r.data = object;r.code = 1;return r;}public static <T> R<T> error(String msg) {R r = new R();r.msg = msg;r.code = 0;return r;}public R<T> add(String key, Object value) {this.map.put(key, value);return this;}}

 6.2.5 在SetmealController的list方法加入@Cacheable注解

package com.runa.reggie.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.dto.SetmealDto;
import com.runa.reggie.entity.Category;
import com.runa.reggie.entity.Setmeal;
import com.runa.reggie.service.CategoryService;
import com.runa.reggie.service.SetmealDishService;
import com.runa.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.stream.Collectors;@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {@Autowiredprivate SetmealService setmealService;@Autowiredprivate CategoryService categoryService;@Autowiredprivate SetmealDishService setmealDishService;/*** 新增套餐* @param setmealDto* @return*/@PostMappingpublic R<String> save(@RequestBody SetmealDto setmealDto){log.info("套餐信息:{}",setmealDto);setmealService.saveWithDish(setmealDto);return R.success("新增套餐成功");}/*** 套餐分页查询* @param page* @param pageSize* @param name* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize, String name){//分页构造器对象Page<Setmeal> pageInfo = new Page<>(page,pageSize);Page<SetmealDto> dtoPage = new Page<>();LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据name进行like模糊查询queryWrapper.like(name != null,Setmeal::getName,name);//添加排序条件,根据更新时间降序排列queryWrapper.orderByDesc(Setmeal::getUpdateTime);setmealService.page(pageInfo,queryWrapper);//对象拷贝BeanUtils.copyProperties(pageInfo,dtoPage,"records");List<Setmeal> records = pageInfo.getRecords();List<SetmealDto> list = records.stream().map((item) -> {SetmealDto setmealDto = new SetmealDto();//对象拷贝BeanUtils.copyProperties(item,setmealDto);//分类idLong categoryId = item.getCategoryId();//根据分类id查询分类对象Category category = categoryService.getById(categoryId);if(category != null){//分类名称String categoryName = category.getName();setmealDto.setCategoryName(categoryName);}return setmealDto;}).collect(Collectors.toList());dtoPage.setRecords(list);return R.success(dtoPage);}/*** 删除套餐* @param ids* @return*/@DeleteMappingpublic R<String> delete(@RequestParam List<Long> ids){log.info("ids:{}",ids);setmealService.removeWithDish(ids);return R.success("套餐数据删除成功");}/*** 根据条件查询套餐数据* @param setmeal* @return*/@GetMapping("/list")@Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")public R<List<Setmeal>> list(Setmeal setmeal){LambdaQueryWrapper<Setmeal> 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<Setmeal> list = setmealService.list(queryWrapper);return R.success(list);}}

6.2.6 在SetmealController的delete方法加入@CacheEvict注解

package com.runa.reggie.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.dto.SetmealDto;
import com.runa.reggie.entity.Category;
import com.runa.reggie.entity.Setmeal;
import com.runa.reggie.service.CategoryService;
import com.runa.reggie.service.SetmealDishService;
import com.runa.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.stream.Collectors;@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {@Autowiredprivate SetmealService setmealService;@Autowiredprivate CategoryService categoryService;@Autowiredprivate SetmealDishService setmealDishService;/*** 新增套餐* @param setmealDto* @return*/@PostMappingpublic R<String> save(@RequestBody SetmealDto setmealDto){log.info("套餐信息:{}",setmealDto);setmealService.saveWithDish(setmealDto);return R.success("新增套餐成功");}/*** 套餐分页查询* @param page* @param pageSize* @param name* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize, String name){//分页构造器对象Page<Setmeal> pageInfo = new Page<>(page,pageSize);Page<SetmealDto> dtoPage = new Page<>();LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据name进行like模糊查询queryWrapper.like(name != null,Setmeal::getName,name);//添加排序条件,根据更新时间降序排列queryWrapper.orderByDesc(Setmeal::getUpdateTime);setmealService.page(pageInfo,queryWrapper);//对象拷贝BeanUtils.copyProperties(pageInfo,dtoPage,"records");List<Setmeal> records = pageInfo.getRecords();List<SetmealDto> list = records.stream().map((item) -> {SetmealDto setmealDto = new SetmealDto();//对象拷贝BeanUtils.copyProperties(item,setmealDto);//分类idLong categoryId = item.getCategoryId();//根据分类id查询分类对象Category category = categoryService.getById(categoryId);if(category != null){//分类名称String categoryName = category.getName();setmealDto.setCategoryName(categoryName);}return setmealDto;}).collect(Collectors.toList());dtoPage.setRecords(list);return R.success(dtoPage);}/*** 删除套餐* @param ids* @return*/@DeleteMapping@CacheEvict(value = "setmealCache" , allEntries = true)public R<String> delete(@RequestParam List<Long> ids){log.info("ids:{}",ids);setmealService.removeWithDish(ids);return R.success("套餐数据删除成功");}/*** 根据条件查询套餐数据* @param setmeal* @return*/@GetMapping("/list")@Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")public R<List<Setmeal>> list(Setmeal setmeal){LambdaQueryWrapper<Setmeal> 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<Setmeal> list = setmealService.list(queryWrapper);return R.success(list);}}

6.2.7 在SetmealController的save方法加入@CacheEvict注解

package com.runa.reggie.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runa.reggie.common.R;
import com.runa.reggie.dto.SetmealDto;
import com.runa.reggie.entity.Category;
import com.runa.reggie.entity.Setmeal;
import com.runa.reggie.service.CategoryService;
import com.runa.reggie.service.SetmealDishService;
import com.runa.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.stream.Collectors;@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {@Autowiredprivate SetmealService setmealService;@Autowiredprivate CategoryService categoryService;@Autowiredprivate SetmealDishService setmealDishService;/*** 新增套餐* @param setmealDto* @return*/@PostMapping@CacheEvict(value = "setmealCache" , allEntries = true)public R<String> save(@RequestBody SetmealDto setmealDto){log.info("套餐信息:{}",setmealDto);setmealService.saveWithDish(setmealDto);return R.success("新增套餐成功");}/*** 套餐分页查询* @param page* @param pageSize* @param name* @return*/@GetMapping("/page")public R<Page> page(int page, int pageSize, String name){//分页构造器对象Page<Setmeal> pageInfo = new Page<>(page,pageSize);Page<SetmealDto> dtoPage = new Page<>();LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();//添加查询条件,根据name进行like模糊查询queryWrapper.like(name != null,Setmeal::getName,name);//添加排序条件,根据更新时间降序排列queryWrapper.orderByDesc(Setmeal::getUpdateTime);setmealService.page(pageInfo,queryWrapper);//对象拷贝BeanUtils.copyProperties(pageInfo,dtoPage,"records");List<Setmeal> records = pageInfo.getRecords();List<SetmealDto> list = records.stream().map((item) -> {SetmealDto setmealDto = new SetmealDto();//对象拷贝BeanUtils.copyProperties(item,setmealDto);//分类idLong categoryId = item.getCategoryId();//根据分类id查询分类对象Category category = categoryService.getById(categoryId);if(category != null){//分类名称String categoryName = category.getName();setmealDto.setCategoryName(categoryName);}return setmealDto;}).collect(Collectors.toList());dtoPage.setRecords(list);return R.success(dtoPage);}/*** 删除套餐* @param ids* @return*/@DeleteMapping@CacheEvict(value = "setmealCache" , allEntries = true)public R<String> delete(@RequestParam List<Long> ids){log.info("ids:{}",ids);setmealService.removeWithDish(ids);return R.success("套餐数据删除成功");}/*** 根据条件查询套餐数据* @param setmeal* @return*/@GetMapping("/list")@Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")public R<List<Setmeal>> list(Setmeal setmeal){LambdaQueryWrapper<Setmeal> 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<Setmeal> list = setmealService.list(queryWrapper);return R.success(list);}}

6.3 功能测试

http://localhost:8080/front/page/login.htmlhttp://localhost:8080/backend/index.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/120643.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

时序预测 | MATLAB实现EEMD-SSA-LSTM、EEMD-LSTM、SSA-LSTM、LSTM时间序列预测对比

时序预测 | MATLAB实现EEMD-SSA-LSTM、EEMD-LSTM、SSA-LSTM、LSTM时间序列预测对比 目录 时序预测 | MATLAB实现EEMD-SSA-LSTM、EEMD-LSTM、SSA-LSTM、LSTM时间序列预测对比预测效果基本介绍模型描述程序设计参考资料 预测效果 基本介绍 时序预测 | MATLAB实现EEMD-SSA-LSTM、E…

《向量数据库指南》——腾讯云向量数据库(Tencent Cloud VectorDB) SDK 正式开源

腾讯云向量数据库 SDK 宣布正式开源。根据介绍,腾讯云向量数据库(Tencent Cloud VectorDB)的 Python SDK 与 Java SDK 是基于数据库设计模型,遵循 HTTP 协议,将 API 封装成易于使用的 Python 与 Java 函数或类,为开发者提供了更加友好、更加便捷的数据库使用和管理方式。…

数据分享|R语言用lme4多层次(混合效应)广义线性模型(GLM),逻辑回归分析教育留级调查数据...

全文链接:http://tecdat.cn/?p22813 本教程为读者提供了使用频率学派的广义线性模型&#xff08;GLM&#xff09;的基本介绍。具体来说&#xff0c;本教程重点介绍逻辑回归在二元结果和计数/比例结果情况下的使用&#xff0c;以及模型评估的方法&#xff08;点击文末“阅读原文…

Java版企业电子采购招标系统源码

一、立项管理 1、招标立项申请 功能点&#xff1a;招标类项目立项申请入口&#xff0c;用户可以保存为草稿&#xff0c;提交。 2、非招标立项申请 功能点&#xff1a;非招标立项申请入口、用户可以保存为草稿、提交。 3、采购立项列表 功能点&#xff1a;对草稿进行编辑&#x…

【Unity3D赛车游戏优化篇】【九】Unity中如何让汽车丝滑漂移?

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…

软件测试人需要掌握的测试知识架构体系(上)

软件计划与可行性研究&#xff08;问题定义、可行性研究&#xff09;&#xff1b;需求分析&#xff1b;软件设计&#xff08;概要设计、详细设计&#xff09;&#xff1b;编码&#xff1b;软件测试&#xff1b;运行与维护。 一、软件的生命周期(SDLC) 1、生存周期划分 各阶段…

软路由ip的优势与劣势:了解其适用场景和限制

在网络技术的快速发展中&#xff0c;软路由IP作为一种灵活且功能强大的网络设备&#xff0c;越来越受到人们的关注。然而&#xff0c;正如任何技术一样&#xff0c;软路由IP也有其优势和劣势。本文将深入探讨软路由IP的优势、劣势以及其适用场景和限制&#xff0c;帮助你更好地…

字节二面:如果高性能渲染十万条数据?

前言 最近博主在字节面试中遇到这样一个面试题&#xff0c;这个问题也是前端面试的高频问题&#xff0c;作为一名前端开发工程师&#xff0c;我们虽然可能很少会遇到后端返回十万条数据的情况&#xff0c;但是了解掌握如何处理这种情况&#xff0c;能让你对前端性能优化有更深的…

Redis 缓存预热+缓存雪崩+缓存击穿+缓存穿透

面试题&#xff1a; 缓存预热、雪萌、穿透、击穿分别是什么&#xff1f;你遇到过那几个情况&#xff1f;缓存预热你是怎么做的&#xff1f;如何造免或者减少缓存雪崩&#xff1f;穿透和击穿有什么区别&#xff1f;他两是一个意思还是载然不同&#xff1f;穿适和击穿你有什么解…

uniApp webview 中调用底座蓝牙打印功能异常

背景: 使用uniApp, 安卓底座 webView 方式开发; 调用方式采用H5 向 底座发送消息, 底座判断消息类型, 然后连接打印机进行打印; 内容通过指令集方式传递给打印机; 过程当中发现部分标签可以正常打印, 但又有部分不行,打印机没反应, 也没有报错; 原因分析: 对比标签内容…

leetcode 141. 环形链表

2023.9.5 环形链表相遇问题&#xff0c;可以定义一对快慢指针&#xff0c;快指针每次向前走两步&#xff0c;慢指针每次向前走一步&#xff0c;如果链表是环形的最终一定会相遇。 代码如下&#xff1a; /*** Definition for singly-linked list.* struct ListNode {* int…

Unity 顶点vertices,uv,与图片贴图,与mesh

mesh就是组成3d物体的三角形们。 mesh由顶点组成的三角形组成&#xff0c;三角形的大小 并不 需要一样&#xff0c;由顶点之间的位置决定。 mesh可以是一个或者多个面。 贴图的原点在左下角&#xff0c;uv是贴图的坐标&#xff0c;数量和顶点数一样&#xff08;不是100%确定…

unity tolua热更新框架教程(2)

Lua启动流程 增加脚本luamain&#xff0c;继承luaclient 建立第一个场景GameMain&#xff0c;在对象GameMain挂载脚本LuaMain&#xff0c;启动场景 看到打印&#xff0c;lua被成功加载 lua入口及调用堆栈 这里会执行main.lua文件的main函数 C#接口导出 在此处配置C#导出的代码 …

CLion远程Linux开发环境搭建及找不到Linux头文件的解决方法

CLion远程开发环境搭建及找不到Linux头文件的解决方法 文章目录 CLion远程开发环境搭建及找不到Linux头文件的解决方法1.前言2.远程开发3.远程编译4.远程调试5.远程开发Linux头文件找不到&#xff08;比如pthread.h、<sys/socket.h>&#xff09;6.最后 1.前言 在某些时候…

苹果“嘴硬”?下载超出预期,否认开发者对 Vision Pro 兴趣不高

据报道&#xff0c;苹果于上个月在全球多个城市开设了Vision Pro开发者实验室&#xff0c;旨在让开发者尽早体验并研发这款令人期待的头显技术。这一为期一天的实验室活动邀请了一些开发人员前来测试和上手Vision Pro头显&#xff0c;并亲身体验其应用的真实效果。 在活动中&am…

【zookeeper】zookeeper的shell操作

Zookeeper的shell操作 本章节将分享一些zookeeper客服端的一些命令&#xff0c;实验操作有助于理解zookeeper的数据结构。 Zookeeper命令工具 在前一章的基础上&#xff0c;在启动Zookeeper服务之后&#xff0c;输入以下命令&#xff0c;连接到Zookeeper服务。连接成功之后&…

【ROS】例说mapserver静态地图参数(对照Rviz、Gazebo环境)

文章目录 例说mapserver静态地图参数1. Rviz中显示的地图2. mapserver保存地图详解3. 补充实验 例说mapserver静态地图参数 1. Rviz中显示的地图 在建图过程中&#xff0c;rviz会显示建图的实时情况&#xff0c;其输出来自于SLAM&#xff0c;浅蓝色区域为地图大小&#xff0c…

SeaTunnel扩展Transform插件,自定义转换插件

代码结构 在seatunnel-transforms-v2中新建数据包名&#xff0c;新建XXXTransform&#xff0c;XXXTransformConfig&#xff0c;XXXTransformFactory三个类 自定义转换插件功能说明 这是个适配KafkaSource的转换插件&#xff0c;接收到的原文格式为&#xff1a; {"path&…

ARP欺骗

1.定义 ARP欺骗&#xff08;英语&#xff1a;ARP spoofing&#xff09;&#xff0c;又称ARP毒化&#xff08;ARP poisoning&#xff0c;网络上多译为ARP病毒&#xff09;或ARP攻击&#xff0c;是针对以太网地址解析协议&#xff08;ARP&#xff09;的一种攻击技术&#xff0c;…

【GAMES202】Real-Time Global Illumination(in 3D)—实时全局光照(3D空间)

一、SH for Glossy transport 1.Diffuse PRT回顾 上篇我们介绍了PRT&#xff0c;并以Diffuse的BRDF作为例子分析了预计算的部分&#xff0c;包括Lighting和Light transport&#xff0c;如上图所示。 包括我们还提到了SH&#xff0c;可以用SH的有限阶近似拟合球面函数&#xff…