DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. 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.

Emmanouil Gkatziouras user avatar by
Emmanouil Gkatziouras
CORE ·
Jan. 11, 17 · Tutorial
Like (16)
Save
Tweet
Share
46.26K Views

Join the DZone community and get the full member experience.

Join For Free

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<UserPayload> 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<UserPayload> 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<UserPayload> payloadUsers;
    private static final Logger LOGGER = LoggerFactory.getLogger(UserRepositoryLocal.class);
    @Override
    @Cacheable("alluserscache")
    public List<UserPayload> 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<UserPayload> 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<UserPayload> 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.

Spring Framework Cache (computing) Spring Boot Abstraction (computer science)

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Asynchronous Messaging Service
  • AWS CodeCommit and GitKraken Basics: Essential Skills for Every Developer
  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Microservices Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: