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 做 缓存的唯一标志

 4 清除缓存 在方法前面加上   @CacheEvict

关于 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 参数说明:

  

maxElementsInMemory:在内存中最大数量的对象数
eternal: 是否 又不过期

timeToIdleSeconds: 多长时间不命中这个对象会被移除缓存

timeToLiveSeconds: 缓存对象最大存活时间
maxElementsOnDisk:最大允许在硬盘中存多少个 对象
diskExpiryThreadIntervalSeconds:在硬盘上的对象多久清除一次
memoryStoreEvictionPolicy:缓存清除算法   LRU(清除最近使用次数最少的)  LFU(清除使用次数最少的) FIFO(先入先出)

  

备注:需要引入 ehcache 的 jar 包

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

备注:因为要 要写入银盘,所以 需要 缓存的对象实现了 Serializable 接口。

备注key  的 格式

  key 可以 使用

  key="#参数" ,

key="#methodName" ,

key="#参数.id"

或者  key="T(String).valueOf(#page).concat('-').concat(#pageSize)" 

或者 直接使用  自定义 key 生成器  keyGenerator = "cacheKeyGenerator"

package com.rynk.award.utils;

import java.lang.reflect.Method;

import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.stereotype.Component;

/**
 * 缓存的key 生成器(  作为缓存 方法参数 的对象,必须要重写 hashCode 方法 )
 * @author ZHANGYUKUNUP
 *
 */
@Component
public class CacheKeyGenerator extends  SimpleKeyGenerator {
    
    @Override
    public Object generate(Object target, Method method, Object... params) {
        StringBuilder key = new StringBuilder();
        key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");
        key.append(  generateKey(params) );
        return key.toString();
    }
	
}

  

值得 一提 的是  @CacheEnable  默认在 Service 层有效,别的层不生效,会抛出 key  空指针,如果 在 feign  的服务调用中 Service 也不可以,这时候需要是使用自定义 Key 生成器就可以了。

原文地址:https://www.cnblogs.com/cxygg/p/12160842.html