Reputation: 325
I start to learn Spring Cache abstraction. I use Spring boot, Spring Data Jpa, EhCache provider for this purpose.
My 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>
My service:
@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);
}
}
My controller:
@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);
}
}
I am performing requests to my controller...
When I perform getAll() method of the controller data are cached correctly and then don't exucute query to database at next times. Then I update and delete data from the database using corresponding methods of my controller, which service methods are marked as @CachePut and @CacheEvict respectively and must refresh cache. Then I perform above getAll() method again and get the same response like at the first time but I want that it will be refreshed after performing delete and update requests.
What's I doing wrong or How I can get the desired result?.
Upvotes: 1
Views: 1771
Reputation: 5978
When you put @Cachable annotation on a method so all entries will be kept on cache added by default a name then the first cachable is different to second cachable, so if you want to work well you need to add a name that you want, for example:
@Cachable("teams")
@Cachable("teams")
@CachePut("teams")
@CacheEvict(value="teams", allEntries=true)
You can get more information in this link: https://www.baeldung.com/spring-cache-tutorial
Perhaps a best solution would be this:
@Cachable("team")
@Cachable("teams")
@Caching(put = {
@CachePut(value="team"),
@CachePut(value="teams") })
@Caching(evict = {
@CacheEvict(value="team", allEntries=true),
@CacheEvict(value="teams", allEntries=true) })
Upvotes: 1