While working with the AWS Java SDK we often used to cache the session variable and reuse it, Earlier I was using the core java and cache the session using the Google Guava Expiring HashMap after migrating all the services to the Springboot, now I started using the Spring Cache abstraction framework but still using the Google Expiring HashMap, later I can migrate to Redis or something if required
Sessions should be cached when possible, because creating a new Session will load all configuration values from the environment, and config files each time the Session is created. Sharing the Session value across all of your service clients will ensure the configuration is loaded the fewest number of times possible.
Getting Started
Below is the Springboot dependencies I have added in the Gradle file
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'com.google.guava:guava:31.0.1-jre'
}
Creating the Cache Configuration
To enable the cache, make use of the Spring annotations, it’s as simple as adding other configurations in the framework, we can enable the cache by simply adding the @EnableCaching annotation to the Cache configuration class
@EnableCaching
@Configuration
public class CacheConfiguration implements CachingConfigurer {
@Override
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {
@Override
protected Cache createConcurrentMapCache(final String name) {
return new ConcurrentMapCache(name,
CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
}
};
return cacheManager;
}
}
Here I am using the Google Guava Cache builder and set the expireAfterWrite to 30 minutes
Caching with Annotation
Once we have enabled the cache, the next action is to bind the caching behaviour with the methods where we are creating the AWS session. let’s see the example for one method ( IamClient )
@Cacheable("iamClient")
public IamClient iamClient(AmazonSessionMapper amazonSessionMapper) {
.............................
return iamClient;
}
In this example, AmazonSessionMapper is my own model where I added the access key secret and session token or the ARN of the account.
Summary
in this article, we discussed caching the AWS session using the Springboot Cachable
Source code of spring-boot caching with some simple examples is added to my Github repo
https://github.com/asvignesh/springcache
Also published on Medium.