I've experience in Spring MVC, but first time using Cache. These are steps that I've done yet.
Step : 1
// In spring config
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("user");
}
// Cached Object
public class CachedUser {
private String username;
private String token;
// Public getter-setter
}
// AuthServiceImp
@Service
public class AuthServiceImp implements AuthService {
@Override
@Cacheable(value="user", key="#token")
@Transactional
public CachedUser loadUserDetailsFromDb(String username, String token) {
// codes here
}
@Override
@CacheEvict(value="user", key="#token")
@Transactional
public void removeUser(String username, String token) {
// codes here
}
}
// My Filter
public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {
AuthService authService = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext())
.getBean(AuthService.class);
CachedUser user = this.authService.loadUserDetailsFromDb(username, authToken);
}
// Controller
@RestController
public class AuthenticationController {
@Autowired
private AuthService authService;
@GetMapping("logout2")
public ResponseModel logout(@RequestAttribute("username") String username,
HttpServletRequest request) {
String token = request.getHeader(tokenHeader);
authService.removeUser(username, token);
return new ResponseModel(200,"Success",null);
}
}
Whenever calling loadUserDetailsFromDb
from AuthenticationTokenFilter
it returns cached object (except in first call obviously). That means @Cacheable(value="user", key="#token")
is working fine.
But even after I logged out and called authService.removeUser()
, calling loadUserDetailsFromDb()
fetches the cached object. That means @CacheEvict(value="user", key="#token")
is not working.
Step: 2
Referred this and moved removeUser()
to another service ( say CacheServiceImp implements CacheService
), yet same problem.
Step: 3
Reffered this and , by my understanding, moved @Cache*
annotation to interface AuthService
, got following error.
java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?)
Note : Is the problem of not evicting, because I'm calling @Cacheable
and @CacheEvict
methods from different classes. That is from AuthenticationTokenFilter
and AuthenticationController