Spring boot 缓存的使用

1 首先 引入配置:

<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-cache</artifactId>
		</dependency>

  

2 然后开始 缓存的使用 

  启动类上加上 注解:@EnableCaching

3 在你要使用的 缓存的 方法上面加上   @Cacheable(value = "缓存的名字",key = "#p1")

    备注 key="#p1" ,表示用参数p1 做 缓存的唯一标志

关于 2 中 缓存 ehche 和 redis

1 如果只是简单的需要一个缓存,不需要 多节共享,不需要对持久换有要求,那么使用ehcahe 之类的 Java嵌入式的缓存 是和合适的。

2 如果需要多节点 共享 ,对数据的格式,持久换要求比较高。那么可以选着 redis 之类的 独立运行的 缓存 工具。

redis 配置: 配置redis 并且制定缓存是 redis( 备注,redis做缓存 @Cacheable 里面必须指定缓存的 名字,ehcache  因为配置文件指定了 默认缓存,所以可以不指定 )

备注1: 可以指定 过期时间,但是这是毫秒数

备注2:可以指定统一的 缓存 前缀,但是这样 @Cacheable  里面 指定的 缓存名就无效了,不建议这么干,默认会使用 @Cacheable  的  value::key 格式 ,配置里面指定了统一前缀 就是  前缀::key 格式,可能造成 缓存的混乱

spring:
  cache:
    type: redis

  redis:
    host: 127.0.0.1
    port: 9736
    database: 0
    password: rds123456

备注: 需要引入redis 的 jar 包

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

  

ehcache 的配置:

  cache:
    ehcache:
      config: classpath:ehcache.xml

  

ehcache 配置文件 反倒对应的 clasPath 下面。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
 
    <diskStore path="java.io.tmpdir"/>
 
  <!--defaultCache:echcache的默认缓存策略  -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <cache name="keyStore" 
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="86400"
            timeToLiveSeconds="86400"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

  

备注:需要引入 ehcache 的 jar 包

<dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>

  

猜你喜欢

转载自www.cnblogs.com/cxygg/p/12160842.html