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?.