How to Integrate CoCache with Redis for Distributed Caching
CoCache integrates with Redis through Spring Boot auto-configuration, automatically creating Redis-backed distributed caches when you annotate interfaces with @CoCache and provide spring.data.redis.* connection properties.
CoCache is a Kotlin-based caching framework that provides a type-safe, annotation-driven approach to distributed caching. When you integrate CoCache with Redis, the framework automatically wires Spring's StringRedisTemplate to handle cache operations while managing JSON serialization and TTL expiration behind the scenes according to the ahoo-wang/cocache source code.
Core Architecture Components
The integration relies on a factory pattern that bridges CoCache's abstraction layer with Redis concrete operations.
RedisDistributedCacheFactory serves as the primary entry point. Located in cocache-spring-redis/src/main/kotlin/me/ahoo/cache/spring/redis/RedisDistributedCacheFactory.kt (lines 46-58), this factory implements DistributedCacheFactory and constructs RedisDistributedCache instances for each @CoCache annotated interface. It automatically resolves the StringRedisTemplate from the Spring context and creates an ObjectToJsonCodecExecutor for serialization.
RedisDistributedCache handles the actual cache operations. Implemented in cocache-spring-redis/src/main/kotlin/me/ahoo/cache/spring/redis/RedisDistributedCache.kt (lines 28-38), this class implements the DistributedCache<V> interface, translating method calls into Redis commands. On reads, it queries Redis for both the value and TTL, then decodes the stored JSON. On writes, it encodes the value and stores it with the configured expiration time.
ObjectToJsonCodecExecutor manages serialization using Jackson. This component, found in cocache-spring-redis/src/main/kotlin/me/ahoo/cache/spring/redis/codec/ObjectToJsonCodecExecutor.kt, converts Kotlin objects to JSON strings for Redis storage and reconstructs them on retrieval.
Step-by-Step Integration Guide
Follow these steps to wire CoCache to your Redis instance.
1. Add the Spring Boot Starter Dependency
Include the CoCache starter in your build configuration:
// build.gradle.kts
implementation("me.ahoo.cocache:cocache-spring-boot-starter")
2. Configure Redis Connection Properties
Spring Boot auto-configures the StringRedisTemplate when you provide Redis settings in application.yaml:
spring:
data:
redis:
host: localhost
port: 6379
cocache:
enabled: true
3. Enable CoCache in Your Application
Use the @EnableCoCache annotation to register your cache interfaces:
@EnableCoCache(caches = [UserCache::class])
@SpringBootApplication
class Application
4. Define Cache Interfaces with @CoCache
Create an interface extending Cache<K, V> and annotate it with @CoCache:
@CoCache(keyPrefix = "user:", ttl = 120)
interface UserCache : Cache<String, User>
The ttl parameter specifies the expiration time in seconds.
5. Inject and Use the Cache
Spring automatically provides the implementation. Simply inject the interface into your services:
@Service
class UserService(private val userCache: UserCache) {
fun getUser(id: String): User? = userCache.get(id)
fun cacheUser(user: User) {
userCache.set(user.id, user)
}
}
Customizing Serialization and Client Caching
While the default JSON codec works for most POJOs, you can provide custom serialization by defining a CodecExecutor bean:
@Bean
fun protobufCodec(redisTemplate: StringRedisTemplate): CodecExecutor<MyProto> {
return ProtobufCodecExecutor(redisTemplate)
}
Place this bean in a @Configuration class. The RedisDistributedCacheFactory will detect and prefer your custom executor over the default ObjectToJsonCodecExecutor.
Monitoring Cache Operations
CoCache exposes management endpoints via Spring Boot Actuator. Once integrated, you can monitor cache statistics and health through the /actuator/cocache endpoint, which displays registered caches and their factory configurations.
Summary
- RedisDistributedCacheFactory automatically creates Redis-backed cache instances when it detects
@CoCacheannotations in the Spring context. - The integration uses StringRedisTemplate for Redis operations and ObjectToJsonCodecExecutor for JSON serialization by default.
- Configuration requires only the CoCache starter dependency and standard
spring.data.redis.*properties. - Cache interfaces extend
Cache<K, V>and use the@CoCacheannotation to define key prefixes and TTL values. - Custom
CodecExecutorbeans override the default JSON serialization for specialized use cases like Protocol Buffers.
Frequently Asked Questions
What dependencies are required to use CoCache with Redis?
You need the cocache-spring-boot-starter dependency, which transitively includes the Redis integration module. Ensure your project also includes Spring Boot's Redis starter or manually configure a StringRedisTemplate bean if not using Spring Boot auto-configuration.
How does CoCache handle serialization for Redis storage?
By default, CoCache uses ObjectToJsonCodecExecutor to serialize values to JSON using Jackson. The RedisDistributedCache stores these JSON strings in Redis with the key prefix defined in @CoCache. You can replace this with custom implementations by providing your own CodecExecutor bean.
Can I set different TTL values for different cache instances?
Yes. Each cache interface annotated with @CoCache has its own ttl parameter measured in seconds. The RedisDistributedCache applies this TTL to every SET operation performed against Redis, allowing per-cache expiration policies.
How does CoCache handle cache misses in a distributed environment?
When RedisDistributedCache.get(key) finds no value in Redis, it returns null or delegates to a client-side cache if configured. The implementation in RedisDistributedCache.kt handles the Redis GET operation and JSON decoding, returning null for missing keys without throwing exceptions.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →