Getting Started with Spring Boot - Advanced (5) - Data Cache (@Cacheable)

Cache can relieve the pressure of database access. Spring itself does not provide cache storage implementation, and needs to rely on third parties, such as JCache, EhCache, Hazelcast, Redis, Guava, etc. Spring Boot can automatically configure the appropriate cache manager (CacheManager), the default is ConcurrentMapCacheManager (java.util.concurrent.ConcurrentHashMap).

(1) Add spring-boot-starter-cache dependency
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>


(2) Turn on the cache function
@Configuration
@EnableCaching
public class CacheConfig {

}


(3) Cached data
For cache operations, there are mainly: @Cacheable, @CachePut, @CacheEvict.

@Cacheable
Spring checks whether there is data in the cache before executing the method annotated with @Cacheable. If there is data, it returns the cached data directly; if there is no data, executes the method and puts the return value of the method into the cache.
Parameters: value cache name, key cache key value, condition satisfies the cache condition, unless vetoes the cache condition
@Cacheable(value = "user", key = "#id")
public User findById(final Long id) {
    System.out.println("cache miss, invoke find by id, id:" + id);
    for (User user : users) {
        if (user.getId().equals(id)) {
            return user;
        }
    }
    return null;
}


@CachePut
is similar to @Cacheable, but will put the return value of the method into the cache, which is mainly used for data addition and modification methods.
@CachePut(value = "user", key = "#user.id")
public User save(User user) {
    users.add(user);
    return user;
}


After the @CacheEvict
method is executed successfully, the corresponding data will be removed from the cache.
Parameters: value cache name, key cache key value, condition satisfies the cache condition, unless denies the cache condition, whether allEntries removes all data (when set to true, all caches will be removed)
@CacheEvict(value = "user", key = "#user.id") // remove the data of the specified key
public User delete(User user) {
    users.remove(user);
    return user;
}

@CacheEvict(value = "user", allEntries = true) // remove all data
public void deleteAll() {
    users.clear();
}


(4) Integrated EhCache

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>


SpringBoot can be automatically configured without any special settings to use.

src/main/resources/ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <cache name="user" maxEntriesLocalHeap="200" timeToLiveSeconds="600">
    </cache>
</ehcache>


src\main\resources/application.properties
quote
spring.cache.ehcache.config=classpath:ehcache.xml


If you want to customize some personalized parameters, configure them in the form of Java Config.
@Configuration
@EnableCaching
public class CacheConfig {

	@Bean
	public CacheManager cacheManager() {
		return new EhCacheCacheManager(ehCacheCacheManager().getObject());
	}

	@Bean
	public EhCacheManagerFactoryBean ehCacheCacheManager() {
		EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean();
		cmfb.setConfigLocation(new ClassPathResource("ehcache.xml"));
		cmfb.setShared(true);
		return cmfb;
	}

}


(5) The combined CacheManager

polls the corresponding Cache from multiple CacheManagers.

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager compositeCacheManager(RedisTemplate<Object, Object> redisTemplate) {
        CompositeCacheManager cacheManager = new CompositeCacheManager(new ConcurrentMapCacheManager(), new SimpleCacheManager());
        cacheManager.setFallbackToNoOpCache(false);
        cacheManager.afterPropertiesSet();
        return cacheManager;
    }

}


*** Set cache invalidation spring.cache.type=none
*** Cached objects must implement Serializable
*** All support Spring transactions except GuavaCacheManager, that is, Cache data will also be removed when rolling back

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326580733&siteId=291194637