SoFunction
Updated on 2025-03-04

SpringBoot implements Read Through mode operation process

Introduction

Read Through mode is usually a caching policy where when an application tries to read data, the cache system is first checked to see if the data already exists in the cache. If data exists in the cache (i.e., cache hits), the data is read directly from the cache and returned to the application. If data does not exist in the cache (i.e., cache misses), the data is read from the underlying data store (such as the database), then load the data into the cache, and finally return it to the application.

The main advantages of this model include:

  • Improve performance: By reducing the number of direct accesses to underlying storage, the performance of data retrieval can be significantly improved.
  • Reduce delay: The cache is usually in memory and has access speeds much faster than disk storage, thus reducing the latency of data retrieval.
  • Reduce database load: By storing frequently accessed data in the cache, the query pressure on the database can be reduced, thereby increasing the throughput of the entire system.

Read Through mode is usually compared with strategies such as Lazy Loading and Eager Loading:

  • Lazy Loading: Data is loaded only when needed, which can reduce unnecessary data loading, but may increase latency for first access.
  • Eager Loading: Preload data, which can reduce the latency of first access, but may increase the application's memory usage and startup time.

When implementing Read Through mode, the following aspects may be considered:

  • Cache invalidation policy: Determines when to remove data from the cache, such as time-based (TTL) or space-based (when the cache reaches a certain size).
  • Concurrent control: Handle the situation where multiple application instances access and modify caches at the same time.
  • Data consistency: Ensure that the data in the cache is consistent with the data in the underlying storage, especially when data is updated.

accomplish

Implementing Read Through mode in Spring Boot can usually be done through Spring Cache abstraction. Spring Cache provides a unified API across different cache implementations and supports multiple cache solutions, such as EhCache, Hazelcast, Infinispan, Redis, etc.

Add dependencies: First, you need to add Spring Boot's cache dependencies and a selected cache implementation library (such as Redis)

<!-- Spring Boot Starter Cache -->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- byRedisAs an example,Add toRedisofSpring Boot Starter -->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Enable cache annotation: Added on Spring Boot configuration class@EnableCachingAnnotation to enable cache annotation support.

Configure the cache manager: Configure one or moreCacheManagerSpring Boot will automatically configure a simpleCacheManager, but you can configure more complex cache policies as needed.

import ;
import ;
import ;
import ;
import ;
@Configuration
public class RedisCacheConfig {
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = ()
                .serializeKeysWith((()))
                .serializeValuesWith((())))
Map<String, RedisCacheConfiguration> customCacheConfigs = new HashMap<>();
("mySpecialCache", 
    ((15))); // Set different expiration times for specific caches                .disableCachingNullValues();
        return (connectionFactory)
                .cacheDefaults(config)
            // You can customize the cache configuration here                .withInitialCacheConfigurations(customCacheConfigs)
                .build();
    }
}

Using cache annotations: Used on methods that require cache@CacheableAnnotation to implement Read Through mode. If there is no data in the cache, the method will be called and the result will be cached.

import ;
import ;
@Service
public class MyService {
    @Cacheable(value = "myCache", key = "#id")
    public MyData getDataById(String id) {
        // Load data from the database        return (id);
    }
}

Cache key value:exist@CacheableSpecifies the cached key value in the annotation, which is usually based on the value of the method parameter.

Cache name: Specify the cache name, which will be used to distinguish different cache domains.

Configure cache parameters: The cached timeout time, conditions, unless conditions, etc. can be configured as needed

value or cacheNames: Specify the cache name. You can specify one or more cache names that will be used to store caches.

@Cacheable(value = "myCacheName", key = "#id")

key: Defines the generation strategy of cached key values. A SpEL expression (Spring Expression Language) is usually used to specify method parameters as cache keys.

@Cacheable(cacheNames = "myCache", key = "#id")

condition: Define the cached conditions and cache them only when the conditions are met.

@Cacheable(cacheNames = "myCache", key = "#id", condition = "#() > 3")

unless: Define the conditions that do not cache, andconditionInstead, it is used to rule out certain situations.

@Cacheable(cacheNames = "myCache", key = "#id", unless = "#result == null")

keyGenerator: Specify a custom cache key generation strategy. If more complex key generation logic is required, you can specify aKeyGeneratorThe name of the bean.

@Cacheable(cacheNames = "myCache", keyGenerator = "myKeyGenerator")

cacheManager: Specify which one to useCacheManager, if there are multipleCacheManagerWhen used.

@Cacheable(cacheNames = "myCache", cacheManager = "myCacheManager")

expireAfterWrite: Set the expiration time (in milliseconds) after cache item is written. This is a commonly used configuration that defines the survival time of cached data.

@Cacheable(cacheNames = "myCache", key = "#id", expireAfterWrite = 3600000) // 1Expired after hours

expireAfterAccess: Set the expiration time after the last access of the cache item, which applies to how long after the cached data expires after the last access.

refreshAfterWrite: Set how long to refresh the cache after writing, suitable for scenarios where cache is dynamically refreshed.

sync: Set whether to create cache items synchronously to prevent race conditions in concurrent environments.

Exception handling: Make sure to handle exceptions that may be thrown in the cache method to avoid affecting the stability of the application.

This is the end of this article about SpringBoot implementing Read Through mode. For more relevant SpringBoot Read Through mode content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!