Library that provides support for auto-configuration of Memcached cache in a Spring Boot application.
It provides implementation for the Spring Cache Abstraction, backed by the Xmemcached. Supports cache eviction per key, as well as clearing out of the entire cache region. Binaries are available from Maven Central.
This project has a dependency on Spring Boot and its projects. The table below outlines the version compatibility matrix between Spring Boot, Java, and the Memcached Spring Boot library version.
| Memcached Spring Boot Version | Spring Boot Version | Java Version |
|---|---|---|
| 3.x.x (Current) | 4.x.x | 17+ |
| 2.0.0 - 2.5.x | 2.x.x - 3.5.x | 8+ |
| 1.0.0 - 1.3.2 | 1.5.x | 8+ |
To plug-in Memcached cache in your application follow the steps below:
-
Include library as a Gradle or Maven compile dependency:
-
Gradle
implementation('io.sixhours:memcached-spring-boot-starter:3.0.0') -
Maven
<dependency> <groupId>io.sixhours</groupId> <artifactId>memcached-spring-boot-starter</artifactId> <version>3.0.0</version> </dependency>
As the default implementation is backed by Xmemcached if there is a requirement to use Spymemcached (i.e. its forked AWS version) following configuation should be applied:
-
Gradle
implementation('io.sixhours:memcached-spring-boot-starter:3.0.0') { exclude group: 'com.googlecode.xmemcached', module: 'xmemcached' } implementation('com.amazonaws:elasticache-java-cluster-client:1.2.3')
-
Maven
<dependency> <groupId>io.sixhours</groupId> <artifactId>memcached-spring-boot-starter</artifactId> <version>3.0.0</version> <exclusions> <exclusion> <groupId>com.googlecode.xmemcached</groupId> <artifactId>xmemcached</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>elasticache-java-cluster-client</artifactId> <version>1.2.3</version> </dependency>
-
-
Snapshot repository
If you want to use
SNAPSHOTversions, add the snapshot-repohttps://oss.sonatype.org/content/repositories/snapshotsas shown in the example.
-
Configure
Memcachedkey-value store in your properties file (application.yml).Example
To manually connect to one or more cache servers (nodes), specify comma-separated list of hostname:port with the
staticprovider:memcached.cache: servers: example1.com:11211,example2.com:11211 provider: static # default expiration set to '1d' (1 day i.e. '86400' seconds) and custom ones for cache_name1 and cache_name2 expiration: 1d expiration-per-cache: cache_name1: 1h cache_name2: 30h metrics-cache-names: cache_name1, cache_name2
To connect to a cluster with AWS Auto Discovery, specify cluster configuration endpoint in
memcached.cache.serversproperty with theawsprovider:memcached.cache: servers: mycluster.example.com:11211 provider: aws expiration: 86400 # default expiration set to '86400' seconds i.e. 1 day
To connect to a cluster within Google App Engine memcached service, it is sufficient to specify the configuration property for provider with value
appengine:memcached.cache: provider: appengine expiration: 86400 # default expiration set to '86400' seconds i.e. 1 day
If you are using authentication to connect to the memcached server, check the example configuration below. The memcached server has to support the authentication mechanism the client is using. By default, the
plainauthentication mechanism will be used, but if needed you can switch toCRAM-MD5mechanism by setting thememcached.cache.authentication.mechanism: cram-md5property.Important: The authentication requires
binaryprotocol, therefore make sure that thememcached.cache.protocolproperty has been set tobinary.memcached.cache: servers: example1.com:11211 provider: static # default expiration set to '1d' (1 day i.e. '86400' seconds) and custom ones for cache_name1 and cache_name2 expiration: 1d authentication: username: my_user # replace with your memcached server 'username' password: my_password # replace with your memcached server 'password' protocol: binary # required for authentication
-
Enable caching support by adding
@EnableCachingannotation to one of your@Configurationclasses.import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Now you can add caching to an operation of your service:
import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; @Component public class BookService { @Cacheable("books") public Book findByTitle(String title) { // ... } }
For further details on using the Memcached cache in a Spring Boot application please look at the demo project.
Properties can be set in your application.yml file or as a command line properties. Below is the
full list of supported properties:
# MEMCACHED CACHE
memcached.cache.servers: # Comma-separated list of hostname:port for memcached servers (default "localhost:11211")
memcached.cache.provider: # Memcached server provider (use one of following: "static", "aws" or "appengine"). Default provider is "static". Use "aws" for AWS node auto discovery, or "appengine" if running on Google Cloud Platform.
memcached.cache.expiration: # Default cache expiration (defaults to "0", meaning that cache will never expire). If duration unit is not specified, seconds will be used by default.
memcached.cache.expiration-per-cache.cacheName: # Set expiration for cache with given name. Overrides `memcached.cache.expiration` for the given cache. To set expiration value for cache named "cacheName" {cache_name}:{number} e.g. "authors: 3600" or "authors: 1h". If duration unit is not specified, seconds will be used by default.
memcached.cache.prefix: # Cache key prefix (default "memcached:spring-boot")
memcached.cache.protocol: # Memcached client protocol. Supports "text" and "binary" protocols (default is "text" protocol)
# Authentication config properties are not required to be set if authentication is not used
memcached.cache.authentication.username: # Login username of the memcached server. Requires "binary" protocol.
memcached.cache.authentication.password: # Login password of the memcached server. Requires "binary" protocol.
memcached.cache.authentication.mechanism: # Authentication mechanism to be used with memcached server. Defaults to "PLAIN". Supported mechanisms are "PLAIN" and "CRAM-MD5".
memcached.cache.operation-timeout: # Memcached client operation timeout (default "2500 milliseconds"). If unit not specified, milliseconds will be used.
memcached.cache.hash-strategy: # Memcached client hash strategy for distribution of data between servers. Supports "standard" (array based : "hash(key) mod server_count"), "libmemcached" (consistent hash), "ketama" (consistent hash), "php" (make easier to share data with PHP based clients), "election", "roundrobin", "random". Default is "standard".
memcached.cache.servers-refresh-interval: # Interval in milliseconds that refreshes the list of cache node hostnames and IP addresses for AWS ElastiCache. The default is 60000 milliseconds.
memcached.cache.metrics-cache-names: # Comma-separated list of cache names for which metrics will be collected.
memcached.cache.disabled-cache-names: # Comma-separated list of cache names for which caching will be disabled. The main purpose of this property is to disable caching for debugging purposes. All of the values have sensible defaults and are bound to MemcachedCacheProperties class.
Duration properties such as expiration and expiration-per-cache by default are using unit of seconds if no unit is specified. For operation-timeout property unit of milliseconds is the default one.
E.g. to specify an expiration of 30 seconds, 30, PT30S (ISO-8601 format) and 30s are all equivalent. An operation-timeout of 500ms can be specified in any of the following form: 500, PT0.5S and 500ms.
Supported units are:
-
nsfor nanoseconds -
usfor microseconds -
msfor milliseconds -
sfor seconds -
mfor minutes -
hfor hours -
dfor days
Notice: If different applications are sharing the same Memcached server, make sure to specify unique cache
prefixfor each application in order to avoid cache conflicts.
The memcached.cache application properties cover the most common configuration options shared across all supported
clients, such as connection setup, timeouts, and basic client behavior.
Spymemcached and Xmemcached clients also expose additional low-level options (such as connection handling, failure strategies, etc.) that are not available through these properties.
If you need more control, you can use client-specific customizer beans. These are applied during Spring Boot
auto-configuration while the client is being created and let you adjust the underlying builder before the client is
instantiated. This allows you to add settings not exposed via memcached.cache or override existing ones when needed.
You can customize
the SpyMemcachedClient
by defining
a SpyMemcachedConnectionFactoryCustomizer
bean. Any such customizer bean is called with the net.spy.memcached.ConnectionFactoryBuilder, which is used internally
to construct the client.
This allows fine-grained control over the underlying client settings, including failure handling, reconnect behavior,
and operation tuning, for example:
@Bean
public SpyMemcachedConnectionFactoryCustomizer customizer() {
return builder -> {
builder.setMaxReconnectDelay(1000);
builder.setFailureMode(FailureMode.Retry);
// overrides 'memcached.cache.operation-timeout' value
// if already specified in application properties
builder.setOpTimeout(1200);
};
}You can customize
the XMemcachedClient
by defining
an XMemcachedClientCustomizer
bean. Any such customizer bean is called with the net.rubyeye.xmemcached.MemcachedClientBuilder, which is used internally
to construct the client.
This allows fine-grained control over the underlying client settings, including connection pooling, timeouts, and other
advanced client features, for example:
@Bean
public XMemcachedClientCustomizer customizer() {
return builder -> {
builder.setConnectionPoolSize(123);
builder.setConnectTimeout(5000);
builder.setFailureMode(true);
// overrides 'memcached.cache.operation-timeout' value
// if already specified in application properties
builder.setOpTimeout(1200);
};
}In order to build the project you will have to have Java 17+ and Docker installed. To build the project invoke the following command:
./gradlew clean build
To install the modules in the local Maven repository:
./gradlew clean build publishToMavenLocal
The CI pipeline uses the [Spotless] Gradle plugin to enforce license headers and code formatting standards. Before submitting changes, format your code by running:
./gradlew spotlessApplyMemcached Spring Boot is an Open Source software released under the Apache 2.0 license.