Spring Cache implementation based on Amazon DynamoDB
To integrate this Git repository into your project, simply add the maven dependency
<dependency>
<groupId>com.dasburo</groupId>
<artifactId>spring-cache-dynamodb</artifactId>
<version>2.0.0</version>
</dependency>
This release is using the AWS Java SDK v2.x. If you must use v1.x, please use a version prior to 2.0.0 of this library.
There is an autoconfiguration class that will set up a simple key-value cache for you, provided you have specified the following properties.
# TTL (in seconds). Default is Duration.ZERO and disables TTL.
spring.cache.dynamo.caches[0].ttl = 10s
# Cache name for the @Cacheable annotation.
spring.cache.dynamo.caches[0].cacheName = myCache
# Value that indicates if the cache must be flushed on application start.
spring.cache.dynamo.caches[0].flushOnBoot = true
spring:
cache:
dynamo:
caches:
- # TTL.
ttl: 10s
# Cache name for the @Cacheable annotation.
cacheName: myCache
# Value that indicates if the cache table must be flushed when the application starts.
flushOnBoot: true
To customize the creation of a cache manager, create a Java Bean in a configuration class:
@Bean
public AwsCredentials awsCredentials() {
return AwsBasicCredentials.create(amazonAWSAccessKey, amazonAWSSecretKey);
}
@Bean
public AwsCredentialsProvider awsCredentialsProvider(AwsCredentials awsCredentials) {
return StaticCredentialsProvider.create(awsCredentials);
}
@Bean
public DynamoDbClient amazonDynamoDB(AwsCredentialsProvider awsCredentialsProvider) {
return DynamoDbClient.builder()
.credentialsProvider(awsCredentialsProvider)
.region(Region.of(amazonAWSRegion))
.build();
}
@Bean
public CacheManager cacheManager(DynamoDbClient ddb) {
List<DynamoCacheBuilder> cacheBuilders = new ArrayList<>();
cacheBuilders.add(DynamoCacheBuilder.newInstance(cacheName, ddb)
.withTTL(Duration.ofSeconds(cacheTtl)));
return new DynamoCacheManager(cacheBuilders);
}
By default, the included StringSerializer
is used. But it's also possible to define a custom Serializer
of type DynamoSerializer
for each cache.
After the cache has been configured, you can use the Cacheable
annotation.
In the following example, the cache "myCache" is used like this:
@Cacheable(value = "myCache", key = "#id")
public Data getData(String id) {
// ...
}
The id
parameter is used as document identifier.
Note that the cache key must be of type java.lang.String
.
It is also possible to use SpEL to generate a combined key.
The Data
object will be stored in a DynamoDB table for future use (as the TTL has not expired).
Note that cache elements must be serializable (i.e. implement java.io.Serializable
).
Spring Cache DynamoDB is Open Source software released under the Apache 2.0 license.