【发布时间】:2019-04-07 15:32:18
【问题描述】:
我开始学习 Spring Cache 抽象。 为此,我使用 Spring boot、Spring Data Jpa、EhCache 提供程序。
我的 ehcache.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ehcache>
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true">
</defaultCache>
<cache name="teams"
maxElementsInMemory="500"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="100"
overflowToDisk="false">
</cache>
我的服务:
@CacheConfig(cacheNames = "teams")
@Service
public class TeamService {
@Autowired
private TeamRepository teamRepository;
@Cacheable
public Team findById(long id) {
return teamRepository.findById(id).get();
}
@Cacheable
public List<Team> findAll() {
return teamRepository.findAll();
}
@CachePut
public Team save(Team team) {
return teamRepository.save(team);
}
@CacheEvict
public void delete(long id) {
teamRepository.deleteById(id);
}
}
我的控制器:
@RestController
public class TeamController {
@Autowired
private TeamService teamService;
@GetMapping("/teams")
public List<Team> getAll() {
return teamService.findAll();
}
@GetMapping("/team/{id}")
public Team getById(@PathVariable long id) {
return teamService.findById(id);
}
@DeleteMapping("/team/{id}")
public void delete(@PathVariable long id) {
teamService.delete(id);
}
@PostMapping("/team")
public Team save(@RequestBody Team team) {
return teamService.save(team);
}
}
我正在向我的控制器执行请求...
当我执行控制器的 getAll() 方法时,数据被正确缓存,然后下次不执行对数据库的查询。然后我使用控制器的相应方法更新和删除数据库中的数据,这些服务方法分别标记为@CachePut 和@CacheEvict 并且必须刷新缓存。然后我再次执行上述 getAll() 方法并获得与第一次相同的响应,但我希望在执行删除和更新请求后刷新它。
我做错了什么或者我怎样才能得到想要的结果?
【问题讨论】:
-
我也有同样的问题。你找到解决办法了吗?
标签: spring-boot caching ehcache spring-cache