# SpringBoot Redis、Ehcache集成和多缓存配置

SpringBoot Redis、Ehcache集成和多缓存配置


Ehcache
  • Ehcache是一个纯java的进程内缓存框架。是Hibernate默认的缓存provider。可以单独使用,一般在三方库中(mybatis、shiro等)使用的较多对分布式支持不够好,多个节点不能同步,通常和redis一块使用。
Ehcache和Redis比较
  • Ehcache直接在Java虚拟机中缓存,缓存共享麻烦。
  • Redis是通过socket访问到缓存服务。如果是单个应用或者对缓存访问要求很高的应用用Ehcache,如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的使用Redis。
Ehcache使用例子
  • 引入依赖
<!-- 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
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整合Ehcache
  • 引入依赖
<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>
  • 启动类添加开启缓存的注解
@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>
  • 测试例子
@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";
}
多缓存配置
  • 缓存配置类:用Redisson和Ehache分别配置。
@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();
    }

}
  • 使用例子
@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 缓存注解
  • @Cacheable

可以标记在一个方法上,也可以标记在一个类上,当标记在方法上时表示该方法是支持缓存的,当标记在一个类上表示该类所有的方法都是支持缓存的。对于一个支持缓存的方法,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。注解常用参数解释如下。

参数 意义
value、cacheNames 缓存的名称,在配置文件中定义,必须指定至少一个。
key 缓存的key,可以为空
cacheManager 缓存的方式,项目可以配置多个缓存方式
  • @CachePut

无论怎样,都将方法的返回结果放到缓存当中。这个注解不会询问是否有缓存好的数据,而是每次都会执行方法,将方法的返回结果放到缓存中,相当于每次都更新缓存中的数据,每次缓存中的数据都是最新的一次缓存数据。

  • @CacheEvict

@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。

  • @Caching

这个注解可以组合多个注解,从而实现自定义注解。

缓存其实存放的是以注解里面的key为key 方法的返回值作为key的value,不是注解里面的value。

猜你喜欢

转载自blog.csdn.net/qq_37248504/article/details/109249651