# SpringBoot Redis, Ehcache integration and multi-cache configuration

SpringBoot Redis, Ehcache integration and multi-cache configuration


Ehcache
  • Ehcache is a pure java in-process caching framework. It is the default cache provider of Hibernate. It can be used alone. Generally used in three-party libraries (mybatis, shiro, etc.), it is not good enough for distributed support. Multiple nodes cannot be synchronized, and it is usually used together with redis.
Comparison of Ehcache and Redis
  • Ehcache caches directly in the Java virtual machine, which is troublesome for cache sharing.
  • Redis accesses the cache service through sockets. If it is a single application or an application that requires high cache access, use Ehcache. If it is a large-scale system, there are cache sharing, distributed deployment, and use of Redis with large cache content.
Ehcache usage example
  • Introduce dependencies
<!-- Ehache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.5</version>
</dependency>
  • Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir/ehcache"/>

    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- HellowWorld 缓存-->
    <cache name="HelloWorldCache"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"></cache>

</ehcache>
  • Test case
@Test
public void test1(){
    
    

    String url = System.getProperty("user.dir");
    System.out.println(url);

    // 创建缓存管理器
    CacheManager cacheManager=CacheManager.create(url+"/javatests/resources/ehcache.xml");
    // 获取缓存对象
    Cache cache=cacheManager.getCache("HelloWorldCache");
    // 创建元素
    Element element=new Element("key1","value1");
    // 将元素添加到缓存
    cache.put(element);

    // 获取缓存
    Element element1=cache.get("key1");
    System.out.println(element1);
    System.out.println(element1.getObjectValue());

    // 删除元素
    cache.remove("key1");
    People people=new People(1,"张三","test");
    Element p1=new Element("test",people);
    cache.put(p1);

    // 获取缓存的信息
    Element element2 = cache.get("test");
    System.out.println(element2);

    // 刷新缓存
    cache.flush();

    // 关闭缓存管理器
    cacheManager.shutdown();
}
SpringBoot integrates Ehcache
  • Introduce dependencies
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.5</version>
</dependency>
  • The startup class adds an annotation to open the cache
@SpringBootApplication
@EnableCaching
@MapperScan("com.li.mapper")
public class TestProjectApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(TestProjectApplication.class);
    }
}
  • Applicaiton.properties
# ehcache配置地址
spring.cache.ehcache.config=ehcache.xml
  • ehache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir/ehcache"/>

    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- HellowWorld 缓存-->
    <cache name="helloworld"
           maxEntriesLocalHeap="1000"
           eternal="false"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>
  • Test example
@RequestMapping("/ehcache/{key}")
@Cacheable(value = "helloworld",key = "#key",cacheManager = "ehacheCacheManager")
public String test4(@PathVariable("key") String key){
    
    
    logger.info("ehcahce,key={}",key);
    return key;
}

@RequestMapping("/default/{key}")
@Cacheable(value = "default",key="#key")
public String cacheDefaultTest(@PathVariable("key") String key) {
    
    
    logger.info("default,key={}", key);
    return "24";
}
Multi-cache configuration
  • Cache configuration class: use Redisson and Ehache to configure separately.
@Configuration
public class CatchConfig {
    
    

    private static final Logger logger= LoggerFactory.getLogger(CatchConfig.class);

    @Autowired
    RedissonClient client;

    @Bean("redissonCacherManager")
    @Primary
    public RedissonSpringCacheManager redissonSpringCacheManager(){
    
    
        RedissonSpringCacheManager cacheManager = new RedissonSpringCacheManager(client);
        logger.info("===========================RedissonSpringCacheManager配置");
        return cacheManager;
    }

    @Bean("ehacheCacheManager")
    public EhCacheCacheManager ehCacheCacheManager(){
    
    
        logger.info("===========================EhCacheCacheManager配置");
        return new EhCacheCacheManager();
    }

}
  • Usage example
@RequestMapping("/ehcache/{key}")
@Cacheable(value = "helloworld",key = "#key",cacheManager = "ehacheCacheManager")
public String test4(@PathVariable("key") String key){
    
    
    logger.info("ehcahce,key={}",key);
    return key;
}
Spring cache annotation
  • @Cacheable

It can be marked on a method or a class. When marked on a method, it means that the method supports caching. When marked on a class, it means that all methods of that class support caching. For a method that supports caching, Spring will cache its return value after it is called to ensure that the next time the method is executed with the same parameters, the result can be obtained directly from the cache without the need to execute the method again. The common parameters are explained as follows.

parameter significance
value、cacheNames The name of the cache, defined in the configuration file, must specify at least one.
key Cached key, can be empty
cacheManager Cache mode, the project can configure multiple cache modes
  • @CachePut

No matter what, put the return result of the method in the cache. This annotation does not ask whether there is cached data, but executes the method every time, putting the return result of the method in the cache, which is equivalent to updating the data in the cache every time, and the data in the cache is the latest each time Cache data once.

  • @CacheEvict

@CacheEvict is used to mark methods or classes that need to clear cache elements. When marked on a class, it means that the execution of all methods in it will trigger the cache clearing operation.

  • @Caching

This annotation can combine multiple annotations to realize custom annotations.

The cache actually stores the key in the annotation as the return value of the key method as the value of the key, not the value in the annotation.

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/109249651