Ehcahce缓存
@Cacheable
查询操作,将查询内容存到缓存里,下次获取时从缓存中获取数据。如果缓存中没有数据,则从数据库中读取,并设置到缓存中
@CachePut
添加/修改操作,当数据库中的数据执行添加修改操作时,缓存中的数据也会进行更新。添加时,则刷新缓存对象;修改时,则更新缓存
注:方法需要返回User对象
@CacheEvict
删除操作,数据库数据删除,对应缓存中的数据也删除
pom.xml 依赖添加
<!--ehcache依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU" />
<!-- 这里的 users 缓存空间是为了下面的 demo 做准备 -->
<cache
name="users"
eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
application.yml
# 设置ehcache缓存的配置
cache:
ehcache:
config: classpath:ehcache.xml
Starter
@EnableCaching//启用缓存
UserController
用户详情查询缓存
@GetMapping("user/id/{userId}")
@Cacheable(value = "users",key = "#userId")
public User queryUserById(@PathVariable Integer userId){
return userService.queryUserById(userId);
}
用户列表查询缓存
// 分页查询
@RequestMapping("list")
@Cacheable(value = "users",key = "#userQuery.pageNum+'-'+#userQuery.pageSize+'-'+#userQuery.userName")
public PageInfo<User> queryUserByPage(UserQuery userQuery){
return userService.queryUserByParams(userQuery);
}
用户更新&删除缓存
//更新用户
@PutMapping("user03")
@CachePut(value = "users",key = "#user.id")
public User updateUser03(@RequestBody @Valid User user){
//调用service层添加方法,返回map对象
userService.updateUser(user);
return user;
}
// 删除用户
@DeleteMapping("user/{userId}")
@CacheEvict(value = "users",key = "#userId")
public Map<String,Object> deleteUser(@PathVariable Integer userId){
Map<String,Object> map = new HashMap<>();
//调用service层添加方法,返回map对象
userService.deleteUserById(userId);
return map;
}