Controller层
@RestController("userDishController")
@Api(tags = "C端-菜品浏览接口")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {
@Autowired
private DishService dishService;
@Autowired
private RedisTemplate redisTemplate;
/**
* 根据分类id查询菜品
* @param categoryId
* @return
*/
@GetMapping("/list")
@ApiOperation("根据分类id查询菜品")
private Result<List<DishVO>> list(Long categoryId){
//构造redis中的key,规则:dish_分类id
String key = "dish_"+categoryId;
//查询redis中是否存在菜品数据
List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
if (list!=null && list.size() > 0){
//如果存在直接返回无需查询数据库
return Result.success(list);
}
Dish dish = new Dish();
dish.setCategoryId(categoryId);
dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
//如果不存在,查询数据库,将查询数据库插入到redis中
List<DishVO> dishVOS = dishService.listWithFlavor(dish);
redisTemplate.opsForValue().set(key, dishVOS);
return Result.success(dishVOS);
}
}
在新增菜品,修改菜品,批量删除菜品,起售、停售菜品时候都需要清除缓存以便显示最新数据。
可以在每个Controller方法完成后加上
Set keys = redisTemplate.keys("dish_*");
redisTemplate.delete(keys);
可以设计一个清理缓存的方法来替代
/**
* 清理缓存数据
* @param pattern
*/
private void cleanCache(String pattern){
Set keys = redisTemplate.keys(pattern);
redisTemplate.delete(keys);
}
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`age` int DEFAULT NULL,
PRIMARY KEY (`id`)
);
@Autowired
private UserMapper userMapper;
//user.id 动态取到用户id,redis通过冒号储存成树形结构
@PostMapping
@CachePut(cacheNames = "userCache",key = "#user.id") //将方法的返回值放入缓存,key的生成为:userCache::user.id
//@CachePut(cacheNames = "userCache",key = "#result.id") //对象导航
//@CachePut(cacheNames = "userCache",key = "#p0.id")//取到第一个参数
//@CachePut(cacheNames = "userCache",key = "#a0.id")
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}
实现类加注解
@Slf4j
@SpringBootApplication
@EnableCaching//开去缓存注解功能
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserMapper userMapper;
//user.id 动态取到用户id,redis通过冒号储存成树形结构
@PostMapping
@CachePut(cacheNames = "userCache",key = "#user.id") //将方法的返回值放入缓存,key的生成为:userCache::user.id
//@CachePut(cacheNames = "userCache",key = "#result.id") //对象导航
//@CachePut(cacheNames = "userCache",key = "#p0.id")//取到第一个参数
//@CachePut(cacheNames = "userCache",key = "#a0.id")
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}
@CacheEvict(cacheNames = "userCache", key = "#id")
@DeleteMapping
public void deleteById(Long id){
userMapper.deleteById(id);
}
@CacheEvict(cacheNames = "userCache" ,allEntries = true)//删除所有键值对缓存
@DeleteMapping("/delAll")
public void deleteAll(){
userMapper.deleteAll();
}
@Cacheable(cacheNames = "userCache",key = "#id")//key的生成为:userCache::id
@GetMapping
public User getById(Long id){
User user = userMapper.getById(id);
return user;
}
@GetMapping("/list")
@ApiOperation("根据分类id查询套餐")
@Cacheable(cacheNames = "setmealCache",key = "#categoryId") //key:setmaelCache::categoryId
public Result<List<Setmeal>> list(Long categoryId){
List<Setmeal> setmeals = setmealService.list(categoryId);
return Result.success(setmeals);
}
/**
* 新增套餐接口
* @param setmealDTO
* @return
*/
@PostMapping
@ApiOperation("新增套餐")
@CacheEvict(cacheNames = "setmealCache" ,key = "#setmealDTO.categoryId")//key:setmealCache::100
public Result save(@RequestBody SetmealDTO setmealDTO){
setmealService.save(setmealDTO);
return Result.success();
}
/**
* 批量删除套餐
* @param ids
* @return
*/
@DeleteMapping
@ApiOperation("批量删除套餐")
@CacheEvict(cacheNames = "setmealCache",allEntries = true)
public Result delete(@RequestParam List<Long> ids){
setmealService.deleteBatch(ids);
return Result.success();
}
/**
* 修改套餐
* @param setmealDTO
* @return
*/
@PutMapping
@ApiOperation("修改套餐")
@CacheEvict(cacheNames = "setmealCache",allEntries = true)
public Result update(@RequestBody SetmealDTO setmealDTO){
setmealService.update(setmealDTO);
return Result.success();
}
冗余字段在特定条件下可以提高查询速度,比如这里的name,image,amount等。因为这样不用联表查询只用查这一张表就好了。
新建Controller层
@RestController
@RequestMapping("/user/shoppingCart")
@Slf4j
@Api(tags = "C端-购物车相关接口")
public class ShoppingCartController {
@Autowired
private ShoppingCartService shoppingCartService;
/**
* 添加购物车
* @param shoppingCartDTO
* @return
*/
@PostMapping("/add")
@ApiOperation("添加购物车")
public Result add(@RequestBody ShoppingCartDTO shoppingCartDTO){
shoppingCartService.addShoppingCart(shoppingCartDTO);
return Result.success();
}
}
ServiceImpl
@Slf4j
@Service
public class ShopppingCartServiceImpl implements ShoppingCartService {
@Autowired
private ShopppingCartMapper shopppingCartMapper;
@Autowired
private DishMapper dishMapper;
@Autowired
private SetmealMapper setmealMapper;
/**
* 添加购物车
* @param shoppingCartDTO
*/
@Override
public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
//判断当前加入购物车的商品已经存在了
ShoppingCart shoppingCart =new ShoppingCart();
BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
Long userId = BaseContext.getCurrentId();
shoppingCart.setUserId(userId);
List<ShoppingCart> list = shopppingCartMapper.list(shoppingCart);
//如果已经存在了,只需要将数量加一
if (list != null && list.size() > 0){
ShoppingCart shoppingCart1 = list.get(0);
shoppingCart1.setNumber(shoppingCart1.getNumber()+ 1 );//update shopping_cart set number = ? where id = ?
shopppingCartMapper.updateNumberById(shoppingCart1);
}else{
//如果不存在,需要插入一条购物车数据
//判断本次添加到购物车的是菜品还是套餐
Long dishId = shoppingCartDTO.getDishId();
Long setmealId = shoppingCartDTO.getSetmealId();
if (dishId != null){
//添加到购物车的是菜品
Dish dish = dishMapper.getById(dishId);
shoppingCart.setName(dish.getName());
shoppingCart.setImage(dish.getImage());
shoppingCart.setAmount(dish.getPrice());
}else {
//本次添加的就是套餐
Setmeal setmeal = setmealMapper.getById(setmealId);
shoppingCart.setName(setmeal.getName());
shoppingCart.setImage(setmeal.getImage());
shoppingCart.setAmount(setmeal.getPrice());
}
shoppingCart.setNumber(1);
shoppingCart.setCreateTime(LocalDateTime.now());
//统一插入
shopppingCartMapper.insert(shoppingCart);
}
}
}
Mapper接口
@Mapper
public interface ShopppingCartMapper {
/**
* 动态条件查询
* @param shoppingCart
* @return
*/
List<ShoppingCart> list(ShoppingCart shoppingCart);
/**
* 根据id修改商品数量
* @param shoppingCart
*/
@Update("update shopping_cart set number = #{number} where id = #{id}")
void updateNumberById(ShoppingCart shoppingCart);
/**
* 插入购物车数据
* @param shoppingCart
*/
@Insert("insert into shopping_cart (name, image, user_id, dish_id, setmeal_id, dish_flavor, amount, number, create_time) VALUES " +
"(#{name} ,#{image} ,#{userId} ,#{dishId} ,#{setmealId} ,#{dishFlavor} ,#{amount} ,#{number} ,#{createTime} )")
void insert(ShoppingCart shoppingCart);
}
XML
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sky.mapper.ShopppingCartMapper">
<select id="list" resultType="com.sky.entity.ShoppingCart">
select * from shopping_cart
<where>
<if test="userId != null">
and user_id = #{userId}
if>
<if test="setmealId != null">
and setmeal_id = #{setmealId}
if>
<if test="dishId != null">
and dish_id = #{dishId}
if>
<if test="dishFlavor != null">
and dish_flavor = #{dishFlavor}
if>
where>
select>
mapper>
Controller层
/**
* 查看购物车
* @return
*/
@GetMapping("/list")
@ApiOperation("查看购物车")
public Result<List<ShoppingCart>> list(){
List<ShoppingCart> shoppingCarts = shoppingCartService.showShopppingCart();
return Result.success(shoppingCarts);
}
Service实现类
/**
* 查看购物车
* @return
*/
@Override
public List<ShoppingCart> showShopppingCart() {
Long userId = BaseContext.getCurrentId();
ShoppingCart shoppingCart = ShoppingCart.builder()
.userId(userId)
.build();
List<ShoppingCart> list = shopppingCartMapper.list(shoppingCart);
return list;
}
Controller层
/**
* 清空购物车
* @return
*/
@DeleteMapping("/clean")
@ApiOperation("清空购物车")
public Result clean(){
shoppingCartService.cleanShoppingCart();
return Result.success();
}
Service实现类
/**
* 清空购物车
*/
@Override
public void cleanShoppingCart() {
Long userId = BaseContext.getCurrentId();
shopppingCartMapper.deleteByUserId(userId);
}
Mapper接口
/**
* 清空购物车
* @param userId
*/
@Delete("delete from shopping_cart where user_id = #{userId}")
void deleteByUserId(Long userId);