- 2023-07-23 13:20:27
- 9495 热度
- 0 评论
上一篇我们学会了如何使用Spring Boot使用进程内缓存在加速数据访问。可能大家会问,那我们在Spring Boot中到底使用了什么缓存呢?
在Spring Boot中通过@EnableCaching
注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:
- Generic
- JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
- EhCache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
除了按顺序侦测外,我们也可以通过配置属性spring.cache.type来强制指定。我们也可以通过debug调试查看cacheManager
对象的实例来判断当前使用了什么缓存。在上一篇中,我们也展示了如何去查看当前使用情况。
当我们不指定具体其他第三方实现的时候,Spring Boot的Cache模块会使用ConcurrentHashMap
来存储。而实际生产使用的时候,因为我们可能需要更多其他特性,往往就会采用其他缓存框架,所以接下来我们会分几篇分别介绍几个常用优秀缓存的整合与使用。
使用EhCache
本篇我们将介绍如何在Spring Boot中使用EhCache进程内缓存。这里我们将沿用上一篇的案例结果来进行改造,以实现EhCache的使用。
先回顾下这个基础案例的三个部分:
User实体的定义
@Entity |
User实体的数据访问实现(涵盖了缓存注解)
@CacheConfig(cacheNames = "users") |
测试验证用例(涵盖了CacheManager的注入,可用来观察使用的缓存管理类)
@Slf4j |
接下来我们通过下面的几步操作,就可以轻松的把上面的缓存应用改成使用ehcache缓存管理。
第一步:在pom.xml
中引入ehcache依赖
<dependency> |
在Spring Boot的parent管理下,不需要指定具体版本,会自动采用Spring Boot中指定的版本号。
第二步:在src/main/resources
目录下创建:ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
完成上面的配置之后,再通过debug模式运行单元测试,观察此时CacheManager已经是EhCacheManager实例,说明EhCache开启成功了。或者在测试用例中加一句CacheManager的输出,比如:
@Autowired |
执行测试输出可以得到:
CacheManager type : class org.springframework.cache.ehcache.EhCacheCacheManager |
可以看到:
- 第一行输出的CacheManager type为
org.springframework.cache.ehcache.EhCacheCacheManager
,而不是上一篇中的ConcurrentHashMap
了。 - 第二次查询的时候,没有输出SQL语句,所以是走的缓存获取
整合成功!欢迎关注本系列教程:《Spring Boot 2.x基础教程》
代码示例
本文的相关例子可以查看下面仓库中的chapter5-2
目录:
- Github:https://github.com/dyc87112/SpringBoot-Learning/
- Gitee:https://gitee.com/didispace/SpringBoot-Learning/
如果您觉得本文不错,欢迎Star
支持,您的关注是我坚持的动力!
- Spring(403)
- Boot(208)
- Spring Boot(187)
- Spring Cloud(82)
- Java(82)
- Cloud(82)
- Security(60)
- Spring Security(54)
- Boot2(51)
- Spring Boot2(51)
- Redis(31)
- SQL(29)
- Mysql(25)
- IDE(24)
- Dalston(24)
- MVC(22)
- JDBC(22)
- IDEA(22)
- mongoDB(22)
- Web(21)
- CLI(20)
- SpringMVC(19)
- Alibaba(19)
- Docker(17)
- SpringBoot(17)
- Git(16)
- Eclipse(16)
- Vue(16)
- ORA(15)
- JPA(15)
- Apache(15)
- Tomcat(14)
- Linux(14)
- HTTP(14)
- Mybatis(14)
- Oracle(14)
- jdk(14)
- Pro(13)
- XML(13)
- JdbcTemplate(13)
- OAuth(13)
- Nacos(13)
- Data(12)
- JSON(12)
- OAuth2(12)
- Myeclipse(11)
- stream(11)
- int(11)
- not(10)
- Bug(10)
- Hystrix(9)
- ast(9)
- maven(9)
- Map(9)
- Swagger(8)
- APP(8)
- Bit(8)
- API(8)
- session(8)
- Window(8)
- HTML(7)
- Github(7)
- JavaMail(7)
- Cache(7)
- File(7)
- IntelliJ(7)
- mail(7)
- windows(7)
- too(7)
- ehcache(6)
- UDP(6)
- RabbitMQ(6)
- and(6)
- star(6)
- Excel(6)
- Log4J(6)
- pushlet(6)
- apt(6)
- read(6)
- Freemarker(6)
- WebFlux(6)
- JSP(6)
- Bean(6)
- error(6)
- nginx(6)
- Server(6)
- jar(6)
- ueditor(6)
- Sentinel(5)
- the(5)
- JWT(5)
- rdquo(5)
- PHP(5)
- Struts(5)
- string(5)
- script(5)
- Syntaxhighlighter(5)
- Tool(5)
- Controller(5)
- swagger2(5)