Create user function:
@Autowired private org.springframework.cache.CacheManager cacheManager;
public boolean createUser(Users user,HttpSession session) {
System.out.println("cache update changed");
Cache c = cacheManager.getCache("defaultCache");
if (c != null) {
System.out.println("hello");
c.put("",user.getUsername());
// this code is not working
}
//BeanPropertySqlParameterSource params = new BeanPropertySqlParameterSource(user);
MapSqlParameterSource params=new MapSqlParameterSource();
params.addValue("username", user.getUsername());
params.addValue("user_session_id", session.getId());
java.util.Date today = new java.util.Date();
//params.addValue("message_time",new java.sql.Timestamp(today.getTime()));
params.addValue("user_last_activity_time", new java.sql.Timestamp(today.getTime()));
jdbc.update("insert into users (username,user_session_id,user_last_activity_time) values (:username,:user_session_id,:user_last_activity_time)", params);// == 1;
//c.clear();
//return user;
return true;
}
Get user function:
@Cacheable(value="defaultCache")
//@CachePut(value="defaultCache")
public List<Users> getOnlineUsers() {
System.out.println("DB Query");
return jdbc.query(sql, new RowMapper<Users>() {
@Override
public Users mapRow(ResultSet rs, int rowNumb) throws SQLException {
Users user = new Users();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
return user;
}
});
}
please help me how can I update the cache on creating new user so when I get users from List<Users> getOnlineUsers()
function by jquery json function i should get updated cache. Thanks
If you want to clear complete cache using @CacheEvict
then you can use allEntries = true
in annotation parameter
@CacheEvict(value="defaultCache", allEntries = true)
public boolean createUser(Users user, HttpSession session) { ....
The exact way of doing this will depend on the cost of loading all users and the number of times users get created.
You basically have two options:
@CacheEvict
so that it happens outside of the transaction that created the user.User
to it. And then put that mapping back in the cache. For that you will need to figure out what Spring caching uses as default key, or specify a key in your @Cacheable
annotation on getOnlineUsers
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With