我的B站主页:https://space.bilibili.com/81170341
一、缓存是什么?
缓存是一种介于数据永久存储介质与数据应用之间的数据临时存储介质
使用缓存可以有效的减少低速数据读取过程的次数(例如磁盘IO),提高系统性能
缓存不仅可以用于提高永久性存储介质的数据读取效率,还可以提供临时的数据存储空间
二、Simple。
导入缓存技术对应的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
启用缓存
@SpringBootApplication
@EnableCaching
public class Springboot19CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot19CacheApplication.class, args);
}
}
设置当前操作的结果数据进入缓存
@Cacheable (value="cacheSpace" ,key="#id")
public Book getById( Integer id) {
return bookDao.selectById(id);
}
三、Ehcache。
加入Ehcache坐标
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
缓存设定为使用Ehcache
spring:
cache:
type: ehcache
ehcache:
config: ehcache.xml
提供ehcache配置文件ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd'
updateCheck="false">
<cache
name="smsCode"
eternal="false"
diskPersistent="false"
maxElements InMemory= "1000"
overflowToDisk="false"
timeToIdleSeconds="10"
timeToLiveSeconds="10"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
四、Redis。
加入redis坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
设置redis相关配置
spring:
redis:
host: localhost
port: 6379
cache :
type: redis
redis:
use-key-prefix: true #是否使用前缀名(系统定义前缀名)
key-prefix: sms_ #追加自定义前缀名
time-to-live: 10s #有效时长
cache-null-values: false #是否允许存储空值