Skip to content

Instantly share code, notes, and snippets.

@ankushs92
Created February 9, 2016 17:27

Revisions

  1. ankushs92 created this gist Feb 9, 2016.
    33 changes: 33 additions & 0 deletions SomeClass.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    // 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;
    }


    }