SpringBoot手动使用EhCache

电脑杂谈  发布时间:2020-03-20 00:08:54  来源:网络整理

spring ehcache_ehcache spring aop_spring aop ehcache

SpringBoot基于Spring的AOP技术在注释级别实现数据缓存功能. 所有高速缓存配置都只能在注释级别进行配置,例如声明性事务.

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

对于不同的缓存技术,需要实现不同的cacheManager. Spring定义了以下cacheManger实现.

CacheManger描述

SimpleCacheManager

使用一个简单的Collection来存储缓存ehcache spring aop,主要用于测试

ConcurrentMapCacheManager

使用ConcurrentMap作为缓存技术(默认)

spring aop ehcache_ehcache spring aop_spring ehcache

NoOpCacheManager

用于测试

EhCacheCacheManager

使用EhCache作为缓存技术,该技术通常在之前的休眠模式中使用

GuavaCacheManager

使用Google番石榴作为缓存技术的GuavaCache

HazelcastCacheManager

使用Hazelcast作为缓存技术

spring ehcache_spring aop ehcache_ehcache spring aop

JCacheCacheManager

使用JCache标准实现作为缓存技术,例如Apache Commons JCS

RedisCacheManager

使用Redis作为缓存技术

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

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的实现类

添加注释@EnableCaching

注释说明

ehcache spring aop_spring ehcache_spring aop ehcache

@可缓存

在调用方法之前,您应该首先在缓存中查找方法的返回值. 如果可以找到该值,它将返回缓存的值. 否则,将调用此方法,并将返回值放入缓存中.

@CachePut

将方法的返回值放入缓存中. 在调用该方法之前不检查缓存,该方法总是被调用.

@CacheEvict

清除缓存中的一个或多个条目.

@缓存

分组的注释. 可以同时应用多个其他缓存的注释.

ehcache spring aop_spring aop ehcache_spring ehcache

在实际的开发过程中,有时不使用注释,而您需要自己添加缓存. 让我们以Ehcache为例,简要介绍配置过程.

引入了springboot-cache和ehcache. 应该注意的是,EhCache不需要配置版本,并且SpringBoot的root 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>

添加注释@EnableCaching

@SpringBootApplication
@EnableCaching
public class DemoApplication {
}

在src \ main \ resources目录中ehcache spring aop,添加ehcache.xml文件.

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

注入SpringBoot自动配置的bean org.springframework.cache.CacheManager.

一个简单的测试类:


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-145388-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...