2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Read Through mode generally refers to a caching strategy in which when an application attempts to read data, the cache system is first checked to see if the data already exists in the cache. If the data exists in the cache (i.e., a cache hit), the data is read directly from the cache and returned to the application. If the data does not exist in the cache (i.e., a cache miss), the data is read from the underlying data store (such as a database), then loaded into the cache, and finally returned to the application.
The main advantages of this model include:
The Read Through pattern is often contrasted with strategies such as Lazy Loading and Eager Loading:
When implementing the Read Through mode, you may need to consider the following aspects:
Implementing the Read Through pattern in Spring Boot can usually be done through the 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 dependency and the selected cache implementation library (such as Redis)
- <!-- Spring Boot Starter Cache -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-cache</artifactId>
- </dependency>
-
- <!-- 以Redis为例,添加Redis的Spring Boot Starter -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- </dependency>
Enable caching annotations: Add to Spring Boot's configuration class@EnableCaching
Annotation to enable cache annotation support.
Configuring the Cache Manager: Configure one or moreCacheManager
, Spring Boot will automatically configure a simpleCacheManager
, but you can configure more complex caching strategies as needed.
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.cache.RedisCacheConfiguration;
- import org.springframework.data.redis.cache.RedisCacheManager;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
-
- @Configuration
- public class RedisCacheConfig {
-
- @Bean
- public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
- RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
- .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
- .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(GenericJackson2JsonRedisSerializer.json())))
-
- Map<String, RedisCacheConfiguration> customCacheConfigs = new HashMap<>();
- customCacheConfigs.put("mySpecialCache",
- config.entryTtl(Duration.ofMinutes(15))); // 为特定缓存设置不同的过期时间
-
- .disableCachingNullValues();
- return RedisCacheManager.builder(connectionFactory)
- .cacheDefaults(config)
- // 在这里可以自定义添加缓存配置
- .withInitialCacheConfigurations(customCacheConfigs)
- .build();
- }
- }
@Cacheable
Annotation 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 org.springframework.cache.annotation.Cacheable;
- import org.springframework.stereotype.Service;
-
- @Service
- public class MyService {
-
- @Cacheable(value = "myCache", key = "#id")
- public MyData getDataById(String id) {
- // 从数据库加载数据
- return myDataRepository.findById(id);
- }
- }
Cache key value:exist@Cacheable
The cache key is specified in the annotation, which is usually based on the value of the method parameter.
Cache Name: Specifies the cache name, which will be used to distinguish different cache domains.
Configuring cache parameters: You can configure the cache timeout, conditions, unless conditions, etc. as needed
value or cacheNames: Specify cache name. You can specify one or more cache names, which will be used to store the cache.
@Cacheable(value = "myCacheName", key = "#id")
key: Defines the generation strategy of cache key values. Usually SpEL expressions (Spring Expression Language) are used to specify method parameters as cache keys.
@Cacheable(cacheNames = "myCache", key = "#id")
condition: Define the conditions for caching, and cache will only be performed when the conditions are met.
@Cacheable(cacheNames = "myCache", key = "#id", condition = "#id.length() > 3")
unless: Defines the conditions for not caching, andcondition
Instead, it is used to exclude certain situations.
@Cacheable(cacheNames = "myCache", key = "#id", unless = "#result == null")
keyGenerator: Specify a custom cache key generation strategy. If you need more complex key generation logic, you can specify aKeyGenerator
The bean name.
@Cacheable(cacheNames = "myCache", keyGenerator = "myKeyGenerator")
cacheManager: Specify whichCacheManager
, if there are multipleCacheManager
Use when.
@Cacheable(cacheNames = "myCache", cacheManager = "myCacheManager")
expireAfterWrite: Set the expiration time after the cache item is written (in milliseconds). This is a common configuration used to define the lifetime of cached data.
@Cacheable(cacheNames = "myCache", key = "#id", expireAfterWrite = 3600000) // 1小时后过期
expireAfterAccess: Set the expiration time of the cache item after the last access, which is applicable to how long after the cached data is last accessed to expire.
refreshAfterWrite: Set how long to refresh the cache after writing. It is suitable for scenarios where the cache is refreshed dynamically.
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 cache methods to avoid affecting the stability of the application.