Lake's Blog Lake's Blog
首页
HCFrame
  • 博客搭建

    • 搜索引擎
    • SEO优化
    • 问题记录
  • Vue

    • 问题记录
  • uni-app
  • 开发

    • Spring
  • 数据库及中间件

    • Elasticsearch
    • SQL
  • 杂谈

    • 杂谈
  • 微服务

    • nacos
    • CAS
  • 算法说明

    • algorithm
  • leetCode

    • leetCode
  • 代理

    • Nginx
  • Linux

    • ubuntu
  • Docker
  • 数据库
  • 消息队列
  • openwrt
  • 友情链接
关于
  • 网站
  • 资源
  • 分类
  • 标签
  • 归档
GitHub

Lake Liu

很菜的程序员
首页
HCFrame
  • 博客搭建

    • 搜索引擎
    • SEO优化
    • 问题记录
  • Vue

    • 问题记录
  • uni-app
  • 开发

    • Spring
  • 数据库及中间件

    • Elasticsearch
    • SQL
  • 杂谈

    • 杂谈
  • 微服务

    • nacos
    • CAS
  • 算法说明

    • algorithm
  • leetCode

    • leetCode
  • 代理

    • Nginx
  • Linux

    • ubuntu
  • Docker
  • 数据库
  • 消息队列
  • openwrt
  • 友情链接
关于
  • 网站
  • 资源
  • 分类
  • 标签
  • 归档
GitHub
  • Spring

    • Spring通过URL传值不能携带"."???
    • Pathvariable注解允许参数为空吗?
    • Spring事务及隔离级别
    • Autowired实现多个实现类
    • SpringBoot集成EhCache
      • CacheManger
      • application配置
      • 入口类配置
      • 缓存注解
      • 手动使用EhCache
        • 1. 添加依赖
        • 2. 入口类配置
        • 3. EhCache配置
        • 4. application.application配置
        • 5. 使用Cache
      • 附录 EhCache.xml
    • SpringBoot如何获取Bean列表
    • SpringBoot通过CacheManager集成redis做缓存
    • Spring不能将包含key值为null的map集合转换成JSON
  • 数据库及中间件

  • 杂谈

  • 微服务

SpringBoot集成EhCache

# SpringBoot集成EhCache

SpringBoot如何集成EhCache

SpringBoot在annotation的层面实现了数据缓存的功能,基于Spring的AOP技术。所有的缓存配置只是在annotation层面配置,像声明式事务一样。

Spring定义了CacheManager和Cache接口统一不同的缓存技术。其中CacheManager是Spring提供的各种缓存技术的抽象接口。而Cache接口包含缓存的各种操作。

# CacheManger

针对不同的缓存技术,需要实现不同的cacheManager,Spring定义了如下的cacheManger实现。

CacheManger 描述
SimpleCacheManager 使用简单的Collection来存储缓存,主要用于测试
ConcurrentMapCacheManager 使用ConcurrentMap作为缓存技术(默认)
NoOpCacheManager 测试用
EhCacheCacheManager 使用EhCache作为缓存技术,以前在hibernate的时候经常用
GuavaCacheManager 使用google guava的GuavaCache作为缓存技术
HazelcastCacheManager 使用Hazelcast作为缓存技术
JCacheCacheManager 使用JCache标准的实现作为缓存技术,如Apache Commons JCS
RedisCacheManager 使用Redis作为缓存技术

常规的SpringBoot已经为我们自动配置了EhCache、Collection、Guava、ConcurrentMap等缓存,默认使用ConcurrentMapCacheManager。SpringBoot的application.properties配置文件,使用spring.cache前缀的属性进行配置。

# application配置

spring.cache.type=#缓存的技术类型
spring.cache.cache-names=应用程序启动创建缓存的名称
spring.cache.ehcache.config=ehcache的配置文件位置
spring.cache.infinispan.config=infinispan的配置文件位置
spring.cache.jcache.config=jcache配置文件位置
spring.cache.jcache.provider=当多个jcache实现类时,指定选择jcache的实现类
1
2
3
4
5
6

# 入口类配置

加入注解 @EnableCaching

# 缓存注解

注解 描述
@Cacheable 在调用方法之前,首先应该在缓存中查找方法的返回值,如果这个值能够找到,就会返回缓存的值。否则,这个方法就会被调用,返回值会放到缓存之中。
@CachePut 将方法的返回值放到缓存中。在方法的调用前并不会检查缓存,方法始终都会被调用。
@CacheEvict 在缓存中清除一个或多个条目。
@Caching 分组的注解,能够同时应用多个其他的缓存注解。

# 手动使用EhCache

在实际开发过程中,存在不使用注解,需要自己添加缓存的情况。下面就以Ehcache为例,简单写一下配置过程。

# 1. 添加依赖

引入springboot-cache和ehcache。需要注意,EhCache不需要配置version,SpringBoot的根pom已经集成了。

    <!-- 缓存 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <!-- ehcache -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
    </dependency>
1
2
3
4
5
6
7
8
9
10

# 2. 入口类配置

加入注解 @EnableCaching

@SpringBootApplication
@EnableCaching
public class DemoApplication {
}
1
2
3
4

# 3. EhCache配置

在src\main\resources目录下,添加ehcache.xml文件,内容见文末。

# 4. application.application配置

# 配置ehcache缓存
spring.cache.type=ehcache
# 指定ehcache配置文件路径
spring.cache.ehcache.config=classpath:/ehcache.xml
1
2
3
4

# 5. 使用Cache

注入SpringBoot自动配置的bean,org.springframework.cache.CacheManager。 一个简单的测试类:

package com.bbf.frame.test;

import com.bbf.frame.Application;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class TestCache {
  @Resource
  private CacheManager cacheManager;

  @Test
  public void cacheTest() {
    // 显示所有的Cache空间
    System.out.println(StringUtils.join(cacheManager.getCacheNames(), ","));
    Cache cache = cacheManager.getCache("userCache");
    cache.put("key", "123");
    System.out.println("缓存成功");
    String res = cache.get("key", String.class);
    System.out.println(res);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# CacheManager转换

    // 获取EhCache的管理器
    org.springframework.cache.ehcache.EhCacheCacheManager cacheCacheManager = (EhCacheCacheManager) cacheManager;
    net.sf.ehcache.CacheManager ehCacheManager = cacheCacheManager.getCacheManager();
    net.sf.ehcache.Cache ehCache = ehCacheManager.getCache("userCache");
1
2
3
4

# 附录 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"
         updateCheck = "false">

  <!-- 指定一个文件目录,当EHCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
  <diskStore path = "java.io.tmpdir"/>

  <!-- 默认的管理策略 -->
  <defaultCache
      eternal = "false"
      maxElementsInMemory = "10000"
      overflowToDisk = "true"
      diskPersistent = "false"
      timeToIdleSeconds = "120"
      timeToLiveSeconds = "120"
      diskExpiryThreadIntervalSeconds = "120"
      memoryStoreEvictionPolicy = "LRU"/>

  <!-- 此缓存最多可以存活timeToLiveSeconds秒,如果期间超过timeToIdleSeconds秒未访问,缓存失效 -->
  <cache
      name = "userCache"
      eternal = "false"
      maxElementsInMemory = "100"
      overflowToDisk = "false"
      diskPersistent = "false"
      timeToIdleSeconds = "120"
      timeToLiveSeconds = "180"
      memoryStoreEvictionPolicy = "LRU"/>

  <!-- maxElementsInMemory 内存中最大缓存对象数,看着自己的heap大小来搞 -->
  <!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false -->
  <!-- maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大 -->
  <!-- overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,
  会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。-->
  <!-- diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区。-->
  <!-- diskPersistent:是否缓存虚拟机重启期数据  -->
  <!-- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒 -->

  <!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,
  如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,
  EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,
  则表示对象可以无限期地处于空闲状态 -->

  <!-- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,
  如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,
  EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,
  则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义 -->

  <!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,
  Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、
  FIFO(先进先出)、LFU(最少访问次数)。-->

</ehcache>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

原文链接:https://segmentfault.com/a/1190000013269653

编辑
#Spring#EhCache#Cache
上次更新: 2020/12/31, 08:07:48
Autowired实现多个实现类
SpringBoot如何获取Bean列表

← Autowired实现多个实现类 SpringBoot如何获取Bean列表→

最近更新
01
IDEA行号太宽
03-11
02
uniapp中实现h5扫码功能(微信版)
08-12
03
Docker安装Rabbitmq
07-22
更多文章>
本站总访问量次 | 您是本站第位访问者
Theme by Vdoing | Copyright © 2020-2024 Lake Liu | MIT License | 背景图、Logo、头像设计@Drrizzee
  • 跟随系统
  • 深色模式
  • 浅色模式
  • 阅读模式