SpringBoot使用缓存

SpringBoot默认使用的缓存技术是Simple(默认)。

添加依赖

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

SpringBoot的启动类上添加@EnableCaching注解。

@Cacheable

在使用缓存的函数上添加@Cacheable(value = "名称空间名称", key = "#方法参数名")注解。

@Cacheable:只会执行一次,当标记在一个方法上时表示该方法是支持缓存的,Spring会在其被调用后将其返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果。

缺点:在特定场景不能使用,如短信验证码,如果是多次获取都会返回第一次计算的验证码。

简单使用示例

@RestController
@RequestMapping("/books")
public class MsgService{

    @Autowired
    private BookDao bookDao;

    @GetMapping("/{id}")
    //value的参数是命名空间名(随便起名),key的参数是方法的参数名,参数名前面一定要加#号
    @Cacheable(value = "cacheSpace", key = "#id")
    public String getById(@PathVariable Integer id) {
        System.out.println("搜索:" + id);
        return bookDao.selectById(1).toString();
    }
}

@CachePut

@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

一般与@Cacheable配合使用。

短信验证码案例

service代码

@Service
public class SMSCodeServiceImpl implements SMSCodeService {

    @Autowired
    private CodeUtils codeUtils;

    @Override
    @CachePut(value = "smsCode", key = "#tele")
    public String sendCodeToSMS(String tele) {
        return codeUtils.generator(tele);
    }

    @Override
    public boolean checkCode(SMSCode sms) {
        String code = sms.getCode();
        String cacheCode = codeUtils.get(sms.getTele());
        return code.equals(cacheCode);
    }
}

controller代码

@RestController
@RequestMapping("/sms")
public class SMSCodeController {

    @Autowired
    private SMSCodeService smsCodeService;

    @GetMapping
    public String getCode(String tele){
        System.out.println("get方法执行了-----------------------");
        return smsCodeService.sendCodeToSMS(tele);
    }

    @PostMapping
    public boolean checkCode(SMSCode sms){
        System.out.println("post方法执行了----------------------");
        return smsCodeService.checkCode(sms);
    }
}

utils代码

public class CodeUtils {
    private final String[] patch = {"000000", "00000", "0000", "000", "00", "0", ""};

    public String generator(String tele) {
        int hash = tele.hashCode();
        long result = hash ^ 429823328 ^ System.currentTimeMillis();
        long code = Math.abs(result % 1000000);
        String codeStr = code + "";
        return patch[codeStr.length()] + codeStr;
    }

    @Cacheable(value = "smsCode", key = "#tele")
    public String get(String tele) {
        return null;
    }
}

整合其它缓存技术

SpringBoot提供的缓存计数提供默认的缓存方案,还可以对其它计数进行整合,统一接口,方便缓存计数的开发与管理。

Ehcache缓存技术

Ehcache是一个纯Java的进程内缓存框架,具有快速、精干等特点。

数据淘汰的配置

  1. volatile-lru:挑选最近最少使用的数据淘汰。
  2. volatile-lfu:挑选最近使用次数最少的数据淘汰。
  3. volatile-ttl:挑选将要过期的数据淘汰。
  4. volatile-random:任意选择数据淘汰。

导入坐标(SpringBoot默认整合了ehcache):

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

application中进行配置:

spring:
  cache:
    type: ehcache
  ehcache:
    config: ehcache.xml

在resources目录下编写Ehcache的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <!-- 磁盘缓存位置 -->
    <diskStore path="C:\Users\Administrator\Desktop\xin"/>
    <!--
        eternal="false"  是否永久存在,设置true则不会被清除,此时与timeout冲突,通常设置为false
        diskPersistent="false"  是否启用磁盘持久化
        maxElementsInMemory="1000"  最大缓存数量
        overflowToDisk="false"      超过最大缓存数量是否持久化到磁盘
        timeToIdleSeconds="60"      最大活动间隔,设置过长缓存容易溢出,设置过短无效果,可用于记录时效性数据,例如验证码。
        timeToLiveSeconds="60"      最大存活时间
        memoryStoreEvictionPolicy="LRU"  缓存清除策略
    -->
    <!--对全体的命名空间进行配置-->
    <defaultCache
        eternal="false"
        diskPersistent="false"
        maxElementsInMemory="1000"
        overflowToDisk="false"
        timeToIdleSeconds="60"
        timeToLiveSeconds="60"
        memoryStoreEvictionPolicy="LRU"/>

    <!--对某个的命名空间进行配置-->
    <cache name="ehcache"
           maxElementsInMemory="10"
           eternal="false"
           timeToIdleSeconds="86400"
           timeToLiveSeconds="86400"
           overflowToDisk="true"
           memoryStoreEvictionPolicy="LRU"/>

</ehcache>

 Ehcache配置文件属性说明

name:缓存名称。    
maxElementsInMemory:缓存最大个数。    
eternal:对象是否永久有效,一但设置了,timeout将不起作用。    
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。
                     仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。    
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。
                     仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。    
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。    
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。    
maxElementsOnDisk:硬盘最大缓存个数。    
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.    
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。    
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。
                             默认策略是LRU(最近最少使用)。
                             你可以设置为FIFO(先进先出)
                             或是LFU(较少使用)。    
clearOnFlush:内存数量最大时是否清除。  

Redis缓存技术

需要先安装redis。

在redis的安装目录,使用命令启动redis:redis-server.exe redis.windows.conf

引入坐标:

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

pom中配置属性:

spring:
  cache:
    type: redis
    redis:
      time-to-live: 60s #设置值的过期时间
      key-prefix: xin_   #key前面加xin为前缀
  redis:
    host: localhost
    port: 6379    #自己redis的启动端口

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值