Spring Cache使用

发布时间 2023-04-06 20:42:10作者: 佛系粥米
package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private UserService userService;


    /**
     * CachePut:将方法返回值放入缓存【基础环境使用map缓存】
     * value:缓存名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * @param user
     * @return
     */
    @CachePut(value = "userCache", key = "#result.id")
    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }

    /**
     * CacheEvict:清理指定缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * @param id
     */
    @CacheEvict(value = "userCache", key = "#id")
    //@CacheEvict(value = "userCache", key = "#p0")
    //@CacheEvict(value = "userCache", key = "#root.args[0]")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }

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

    /**
     * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * condition:满足条件时才缓存数据
     *  @param id
     * @return
     */
    @Cacheable(value = "userCache", key = "#id", condition = "#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<User> list(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId()!=null, User::getId, user.getId());
        queryWrapper.eq(user.getName()!=null, User::getName, user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }
}