缓存
SpringBoot提供了缓存技术,方便缓存的使用
pom.xml导入缓存相关的起步依赖
<!--缓存功能的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
SpringBoot启动类,添加@EnableCaching注解,启用缓存
@SpringBootApplication
@EnableCaching //此注解表示开启缓存功能
public class Springboot4CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot4CacheApplication.class, args);
}
}
业务层组件,使用@Cacheable注解
value属性:存放缓存的位置,可随意定义
key属性:使用 #
+ 参数名
的方式设置缓存的数据
@Override
@Cacheable(value = "cacheSpace",key = "#id")
public Book getById(Integer id){
return bookMapper.selectById(id);
}
常见的SpringBoot可整合的缓存技术
:
需求
需求分析
lombok快速开发实体类
:
<!--导入lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
–
import lombok.Data;
/**
* @author .29.
* @create 2023-04-02 22:08
* 使用@Data注解,提供Getter、Setter和toString()
*/
@Data
public class SMSCode {
//电话号码
private String phoneNumber;
//验证码
private String code;
}
业务层接口
:
/**
* @author .29.
* @create 2023-04-02 22:12
*/
public interface SMSCodeService {
//模拟向sm卡发送验证码
public String sendCodeToSMS(String phoneNumber);
//验证验证码是否正确
public boolean checkCode(SMSCode smsCode);
}
业务层接口实现类
:
/**
* @author .29.
* @create 2023-04-02 22:15
*/
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
@Autowired
private CodeUtils utils; //自动装配工具类对象(工具类中提供了生成验证码的算法)
@Override
//@Cacheable注解不适用,缓存会被读取,导致前后两次验证码重复
//@Cacheable(value="smsCode",key = "#phoneNumber")
//@CachePut注解,缓存只可放不可读
@CachePut(value="smsCode",key = "#phoneNumber")
public String sendCodeToSMS(String phoneNumber) {
return utils.generator(phoneNumber);
}
@Override
public boolean checkCode(SMSCode smsCode) {
//取出内存中的验证码与传递过来的参数比对,如果相同,返回true
String code = smsCode.getCode();
String cacheCode = utils.get(smsCode.getPhoneNumber());
return cacheCode.equals(code);
}
}
工具类实现
:
/**
* @author .29.
* @create 2023-04-02 22:26
*/
@Component
public class CodeUtils {
//为不足六位数的验证码补0用
private String[] patch = {"000000","00000","0000","000","00","0",""};
//加密,生成验证码
public String generator(String phoneNumber){
//获取手机号的hashCode值
int hash = phoneNumber.hashCode();
//设置一个加密码
int encryption = 20230209;
//获取第一次加密结果
long result = hash ^ encryption;
//第二次加密,第一次加密结果与当前时间进行异或操作
long nowTime = System.currentTimeMillis();
result = result ^ nowTime;
//获取第二次加密结果的后六位
long code = result % 1000000;
code = code < 0 ? -code : code;//避免验证码为负值
//转化为字符串
String codeStr = code+"";
int len = codeStr.length();
return patch[len]+codeStr;
}
//设置phoneNumber的缓存,方法返回值为null,有缓存则返回缓存数据,没有才返回null
@Cacheable(value="smsCode",key = "#phoneNumber")
public String get(String phoneNumber){
return null;
}
}
/**
* @author .29.
* @create 2023-04-02 22:16
*/
//用于标记控制器类。@RestController 是 @Controller 和 @ResponseBody 的组合注解,用于标记 RESTful 风格的控制器类。
@RestController
@RequestMapping("/sms")
public class SMSCodeController {
@Autowired
private SMSCodeService service; //自动装配业务层组件
//获取验证码
@GetMapping
public String getCode(String phoneNumber){
String code = service.sendCodeToSMS(phoneNumber);
return code;
}
//判断验证码是否正确
@PostMapping
public boolean checkCode(SMSCode smsCode){
boolean result = service.checkCode(smsCode);
return result;
}
}
@SpringBootApplication
@EnableCaching //此注解表示开启缓存功能
public class Springboot4CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot4CacheApplication.class, args);
}
}
运行案例工程
:
使用国产postMAN测试功能
:
pom.xml导入Ehcache依赖
:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
application.yml配置文件
spring:
cacahe:
type: 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">
<diskStore path="D:\ehcache" />
<!--默认缓存策略 -->
<!-- external:是否永久存在,设置为true则不会被清除,此时与timeout冲突,通常设置为false-->
<!-- diskPersistent:是否启用磁盘持久化-->
<!-- maxElementsInMemory:最大缓存数量-->
<!-- overflowToDisk:超过最大缓存数量是否持久化到磁盘-->
<!-- timeToIdleSeconds:最大不活动间隔,设置过长缓存容易溢出,设置过短无效果,可用于记录时效性数据,例如验证码-->
<!-- timeToLiveSeconds:最大存活时间-->
<!-- memoryStoreEvictionPolicy:缓存清除策略-->
<defaultCache
eternal="false"
diskPersistent="false"
maxElementsInMemory="1000"
overflowToDisk="false"
timeToIdleSeconds="60"
timeToLiveSeconds="60"
memoryStoreEvictionPolicy="LRU" />
<cache
name="smsCode"
eternal="false"
diskPersistent="false"
maxElementsInMemory="1000"
overflowToDisk="false"
timeToIdleSeconds="10"
timeToLiveSeconds="10"
memoryStoreEvictionPolicy="LRU" />
</ehcache>