一、redis安装
安装步骤
tar -xzvf redis-7.0.8.tar.gz
切进文件夹执行以下两条命令
make
make install PREFIX=/home/xwl/app/redis-7.0.8
切入bin目录设置软连接
sudo ln /home/xwl/app/redis-7.0.8/bin/redis-server redis-server
sudo ln /home/xwl/app/redis-7.0.8/bin/redis-cli redis-cli
全局执行redis-server命令即可启动redis数据库,打开新的命令行执行redis-cli即可操作数据库。
二、在spring-boot中使用redis
安装依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
添加配置,redis默认未设置密码,可在redis.conf中修改
spring:
redis:
localhost: localhost
port: 6379
# redis有0-15一共16个数据库
database: 7
password:
# listen-pattern: __keyevent@7__:expired
jedis:
pool:
max-active: 50
max-wait: 3000
max-idle: 20
min-idle: 2
timeout: 5000
编写RedisService
package com.xia.xiatest.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String,String> redisTemplate;
// 写入缓存
public Boolean save(String key, String value) {
boolean result = false;
try {
// 30s后失效
redisTemplate.opsForValue().set(key,value,30, TimeUnit.SECONDS);
result = true;
} catch (Exception e){
e.printStackTrace();
}
return result;
}
// 读取缓存
public String readRedis(String key) {
return redisTemplate.opsForValue()
.get(key);
}
// 更新缓存
public boolean getAndSet(String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
// 删除缓存
public boolean del(String key) {
boolean result = false;
try {
redisTemplate.delete(key);
result = true;
} catch(Exception e){
e.printStackTrace();
}
return result;
}
}
三、以邮件发送验证码为例使用redis设置验证码发送时效
安装邮件依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
设置第三方发送邮件配置
spring:
mail:
host: smtp.qq.com
# port: 587
protocol: smtp
username: 发件人地址
password: 邮箱里获取的第三方授权码
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
发送邮件工具类
package com.xia.xiatest.utils;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class EmailUtil {
// 验证邮箱地址是否正确
public static boolean isValidEmailAddress(String email){
boolean result = true;
try {
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
} catch (AddressException e) {
e.printStackTrace();
result = false;
}
return result;
}
// 产生验证码
public static String genVertificationCode() {
String[] strArr = {"0","1","2","3","4","5","6","7","8","9","0","A","B",
"C","D","E","F","G","H","I","J","K","L","M","N","O", "P","Q","R",
"S","T", "U","V","W","X","Y","Z","a","b", "c","d","e","f","g","h",
"i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// 将数组转为List
List<String> verificationCharts = Arrays.asList(strArr);
// 打乱顺序
Collections.shuffle(verificationCharts);
String result = "";
for(int i = 0; i < 6; i++) {
result += verificationCharts.get(i);
}
return result;
}
}
EmailService类
package com.xia.xiatest.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Autowired
private RedisService redisService;
/**
* 发送邮件方法
* @param to 收件人邮件地址
* @param subject 主题
* @param text 正文
*/
public void sendSimpleMessage(String to, String subject, String text) {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(text);
mailSender.send((simpleMailMessage));
}
/**
* 将邮箱和验证码存入redis
* @param emailAddress
* @param verificationCode
* @return
*/
public Boolean saveEmailToRedis(String emailAddress, String verificationCode) {
String exists = redisService.readRedis(emailAddress);
// 如果redis中存在该emailAddress就不再发送验证码
if(exists == null){
redisService.save(emailAddress, verificationCode);
return true;
}else {
return false;
}
}
}
在Controller中使用
@GetMapping("/sendEmail")
public Result sendEmail(@RequestParam("emailAddress") String emailAddress) {
// 检查邮件地址是否有效
boolean validEmailAddress = EmailUtil.isValidEmailAddress(emailAddress);
if(validEmailAddress){
// 验证该邮箱是否在数据库中已经注册
boolean r = userService.checkEmailRegistered(emailAddress);
if(r){
throw new SystemException(602);
}else {
String code = EmailUtil.genVertificationCode();
boolean send = emailService.saveEmailToRedis(emailAddress,code);
if(send) {
emailService.sendSimpleMessage(emailAddress, Constants.EMAIL_SUBJECT,"您的验证码是:" + code);
return Result.success();
}else{
throw new SystemException(603);
}
}
} else {
throw new SystemException(601);
}
}
}