Reputation: 303
I'm trying to follow Micronaut guide and I've created a simple project. All I wanted to test is removing entries from the cache after 1 minute, but it seems it doesn't work. Could you tell me, what am I missing please? I also tried to implement RemovalListener, but it didn't work and I also don't know, what should the handler in that example do.
My code:
application.properties
micronaut.application.name=caffeinecachetest
micronaut.caches.user.expire-after-write=1m
micronaut.caches.user.listen-to-removals=true
micronaut.caches.user.listen-to-evictions=true
@Serdeable
public class User {
private List<String> roles;
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User{" + "roles=" + roles + '}';
}
}
@Singleton
@CacheConfig(cacheNames = "user")
public class CaffeineService {
Map<String, User> users = new HashMap<>();
@Cacheable
public User getUser(String authorization) {
return users.get(authorization);
}
@CachePut(parameters = {"authorization"})
public void storeUser(String authorization, User user) {
users.put(authorization, user);
}
@CacheInvalidate(parameters = {"authorization"})
public void removeUser(String authorization) {
users.remove(authorization);
}
}
@Controller
public class CaffeineController {
private final CaffeineService caffeineService;
public CaffeineController(CaffeineService caffeineService) {
this.caffeineService = caffeineService;
}
@Get("/{authorization}")
public User getUser(String authorization) {
User user = caffeineService.getUser(authorization);
if (user != null) {
System.out.println("User found in cache");
return user;
}
System.out.println("Creating new User");
caffeineService.storeUser(authorization, createUser());
return null; // I don't want to return it, when we create it
}
private User createUser() {
List<String> roles = new ArrayList<>();
roles.add("first");
roles.add("second");
User user = new User();
user.setRoles(roles);
return user;
}
}
Upvotes: 0
Views: 252