Skip to content

Instantly share code, notes, and snippets.

@ankushs92
Created February 9, 2016 17:27
Show Gist options
  • Save ankushs92/16a9b97d67daa445bf8b to your computer and use it in GitHub Desktop.
Save ankushs92/16a9b97d67daa445bf8b to your computer and use it in GitHub Desktop.
Spring security cache User object when working with JWT.
// Jwt requires an authentication on every request.Assuming that you are storing your User objects in a relational database like MySQL,
// and that your API gets moderate traffic,it is not a good idea to fetch the User object directly from the database every time.
//Instead,once it is retreived ,we cache it locally using Spring Caching abstraction.The cache backend is Google guava.
public class UserServiceImpl implements UserService { //Which further extends UserDetailsService .
@Override
@Cacheable(cacheNames=CacheConstants.USER_CACHE,key="#username") // We cache this guy by its username.
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
final User user = userRepository.findOneByEmail(username);
if(user==null){
throw new UsernameNotFoundException("User with username " + username + " not found");
}
return user;
}
}
//This is the cache used.
public class CacheConfig{
@Bean(name="localGauvaCaches")
public SimpleCacheManager localGuavaCaches(){
final SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
final GuavaCache userCache = new GuavaCache(CacheConstants.USER_CACHE,CacheBuilder.newBuilder()
.concurrencyLevel(3) //Choose per your own will.
.expireAfterAccess(2, TimeUnit.MINUTES) //Expire if not accessed within 2 minutes.
.maximumSize(1000).build()); //For a maximum of 1000 User Objects.
simpleCacheManager.setCaches(Arrays.asList(userCache));
return simpleCacheManager;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment