Spring Boot and Cache Abstraction

Spring Boot and Cache Abstraction
Spring Boot and Cache Abstraction
Caching is a major component in most applications. Fortunately, Spring comes with an in-memory cache, which is pretty easy to set up.

Caching is a major component of most applications, and as long as we try to avoid disk access it will remain important.

Spring has great support for caching with a wide range of configurations. You can start as simple as you want and progress to something much more customizable.

This would be an example with the simplest form of caching that Spring provides. Spring comes by default with an in-memory cache that doesn't take a lot of work to get going.

Let us start with our Gradle file.

group 'com.gkatzioura' version '1.0-SNAPSHOT' buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.2.RELEASE") } } apply plugin: 'java' apply plugin: 'idea' apply plugin: 'org.springframework.boot' repositories { mavenCentral() } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-cache") compile("org.springframework.boot:spring-boot-starter") testCompile("junit:junit") } bootRun { systemProperty "spring.profiles.active", "simple-cache" }

Since the same project will be used for different cache providers, there are going to be multiple Spring profiles. The Spring profile for this tutorial would be the simple-cache because we are going to use the ConcurrentMap-based Cache, which happens to be the default.

We will implement an application that will fetch user information from our local file system. The information should reside on the users.json file.

[ {"userName":"user1","firstName":"User1","lastName":"First"}, {"userName":"user2","firstName":"User2","lastName":"Second"}, {"userName":"user3","firstName":"User3","lastName":"Third"}, {"userName":"user4","firstName":"User4","lastName":"Fourth"} ]

Also we will specify a simple model for the data to be retrieved.

package com.gkatzioura.caching.model; /** * Created by gkatzioura on 1/5/17. */ public class UserPayload { private String userName; private String firstName; private String lastName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }

Then we will add a bean that will read the information.

package com.gkatzioura.caching.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.gkatzioura.caching.model.UserPayload; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.io.Resource; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by gkatzioura on 1/5/17. */ @Configuration @Profile("simple-cache") public class SimpleDataConfig { @Autowired private ObjectMapper objectMapper; @Value("classpath:/users.json") private Resource usersJsonResource; @Bean public List payloadUsers() throws IOException { try(InputStream inputStream = usersJsonResource.getInputStream()) { UserPayload[] payloadUsers = objectMapper.readValue(inputStream,UserPayload[].class); return Collections.unmodifiableList(Arrays.asList(payloadUsers)); } } }

Obviously, in order to access the information, we will use the instantiated bean containing all the user information.

The next step will be to create a repository interface to specify the methods that will be used.

package com.gkatzioura.caching.repository; import com.gkatzioura.caching.model.UserPayload; import java.util.List; /** * Created by gkatzioura on 1/6/17. */ public interface UserRepository { List fetchAllUsers(); UserPayload firstUser(); UserPayload userByFirstNameAndLastName(String firstName,String lastName); }

Now let’s dive into the implementation, which will contain the cache annotations needed.

package com.gkatzioura.caching.repository; import com.gkatzioura.caching.model.UserPayload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; /** * Created by gkatzioura on 12/30/16. */ @Repository @Profile("simple-cache") public class UserRepositoryLocal implements UserRepository { @Autowired private List payloadUsers; private static final Logger LOGGER = LoggerFactory.getLogger(UserRepositoryLocal.class); @Override @Cacheable("alluserscache") public List fetchAllUsers() { LOGGER.info("Fetching all users"); return payloadUsers; } @Override @Cacheable(cacheNames = "usercache",key = "#root.methodName") public UserPayload firstUser() { LOGGER.info("fetching firstUser"); return payloadUsers.get(0); } @Override @Cacheable(cacheNames = "usercache",key = "{#firstName,#lastName}") public UserPayload userByFirstNameAndLastName(String firstName,String lastName) { LOGGER.info("fetching user by firstname and lastname"); Optional user = payloadUsers.stream().filter( p-> p.getFirstName().equals(firstName) &&p.getLastName().equals(lastName)) .findFirst(); if(user.isPresent()) { return user.get(); } else { return null; } } }

Methods that contain @Cacheable will trigger cache population contrary to methods that contain @CacheEvict, which trigger cache eviction.

By using @Cacheable instead of just specifying the cache map that our values will be stored, we can proceed into specifying keys also based on the method name or the method arguments. Thus we achieve method caching.

For example, the method firstUser uses as a key the method name, whilst the method userByFirstNameAndLastName uses the method arguments in order to create a key.

Two methods with the @CacheEvict annotation will empty the caches specified.

LocalCacheEvict will be the component that will handler the eviction.

package com.gkatzioura.caching.repository; import org.springframework.cache.annotation.CacheEvict; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; /** * Created by gkatzioura on 1/7/17. */ @Component @Profile("simple-cache") public class LocalCacheEvict { @CacheEvict(cacheNames = "alluserscache",allEntries = true) public void evictAllUsersCache() { } @CacheEvict(cacheNames = "usercache",allEntries = true) public void evictUserCache() { } }

Because we use a very simple form of cache ttl, eviction is not supported. Therefore, we will add a scheduler only for this particular case, which will evict the cache after a certain period of time.

package com.gkatzioura.caching.scheduler; import com.gkatzioura.caching.repository.LocalCacheEvict; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * Created by gkatzioura on 1/7/17. */ @Component @Profile("simple-cache") public class EvictScheduler { @Autowired private LocalCacheEvict localCacheEvict; private static final Logger LOGGER = LoggerFactory.getLogger(EvictScheduler.class); @Scheduled(fixedDelay=10000) public void clearCaches() { LOGGER.info("Invalidating caches"); localCacheEvict.evictUserCache(); localCacheEvict.evictAllUsersCache(); } }

To wrap up, we will use a controller to call the methods specified.

package com.gkatzioura.caching.controller; import com.gkatzioura.caching.model.UserPayload; import com.gkatzioura.caching.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * Created by gkatzioura on 12/30/16. */ @RestController public class UsersController { @Autowired private UserRepository userRepository; @RequestMapping(path = "/users/all",method = RequestMethod.GET) public List fetchUsers() { return userRepository.fetchAllUsers(); } @RequestMapping(path = "/users/first",method = RequestMethod.GET) public UserPayload fetchFirst() { return userRepository.firstUser(); } @RequestMapping(path = "/users/",method = RequestMethod.GET) public UserPayload findByFirstNameLastName(String firstName,String lastName ) { return userRepository.userByFirstNameAndLastName(firstName,lastName); } }

Last but not least, our Application class should contain two extra annotations. @EnableScheduling is needed in order to enable schedulers and @EnableCaching should be there to enable caching.

package com.gkatzioura.caching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.scheduling.annotation.EnableScheduling; /** * Created by gkatzioura on 12/30/16. */ @SpringBootApplication @EnableScheduling @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }

You can find the source code on GitHub .