SpringBoot----缓存使用
缓存:
-
缓存是一种介于数据永久存储介质与数据应用之间的数据临时存储介质
-
使用缓存可以有效的减少低速数据读取过程的次数(例如磁盘IO),提高系统性能
-
缓存不仅可以用于提高永久性存储介质的数据读取效率,还可以提供临时的数据存储空间
1.手动设置缓存:
(1)第一种:从数据库获取值
(2)第二种:从外部进行获取
2.SpringBoot提供的缓存技术
1、添加cache的坐标
<!-- cache 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、进行开启cache
@EnableCaching是进行开启cache缓存的
3、进行使用缓存
使用@Cacheable(value = "test",key = "#id")表示:
给缓存进行开辟一个空间test,空间中键的为id
案例(使用默认的cache):
进行邮箱验证:
写一个工具类进行对验证码的随机性:
/**
* 处理验证码,进行随机输出
*/
写一个Controller层:
下图是生成验证码:
下图是进行比较验证码是否正确:
使用redis进行缓存
1、导入redis的坐标
<!-- 加载NoSql redis操作的坐标-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 使用客户端jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2、进行配置redis缓存
spring
其中使用前缀和设置前缀是由冲突的,建议使用默认值
并且缓存空值默认是false,这样我们只需要进行设置最大的缓存存活时间
3、案例
不需要进行修改前面使用cache进行缓存的操作,因为在配置中cache缓存使用的redis。(也就是使用默认的cache)案例不用修改
在使用redis进行缓存时,我们需要在yml中去进行配置即可:
srping
进行使用redis缓存。这就可以进行完成使用redis进行缓存。
这样就能结合前的SpringBoot整合JavaMail 去实现一个QQ邮箱的一个验证,常用于登录页面进行验证。
v