Spring Cache是一個框架,實現了基于注解的緩存功能,只需要簡單地加一個注解,就能實現緩存功能。
Spring Cache提供了一層抽象,底層可以切換不同的緩存實現,例如:
①EHCache
②Caffeine
③Redis
常用注解:
代碼開發:
package com.itheima.controller;import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {@Autowiredprivate UserMapper userMapper;@PostMapping@CachePut(cacheNames = "userCache",key="#user.id")//如果使用Spring Cache緩存數據,key的生成:userCache::1public User save(@RequestBody User user){userMapper.insert(user);return user;}@DeleteMapping@CacheEvict(cacheNames = "userCache",key = "#id")public void deleteById(Long id){userMapper.deleteById(id);}@DeleteMapping("/delAll")@CacheEvict(cacheNames = "userCache",allEntries = true)public void deleteAll(){userMapper.deleteAll();}@GetMapping@Cacheable(cacheNames = "userCache",key = "#id")//key的生成:userCache::10public User getById(Long id){User user = userMapper.getById(id);return user;}}