作者:拍友2702938227 | 来源:互联网 | 2023-07-26 14:43
Spring Boot优雅集成发送短信验证码 超详细 有源码
- 一、环境介绍
- 二、创建Spring Boot项目
- 三、创建数据库
- 四、 配置项目基本环境
- 五、具体代码
- 六、项目结构图
- 项目下载地址
一、环境介绍
这里主要介绍一下实用的工具及环境版本:
- 工具 :IntelliJ IDEA 2019.2.4 x64;
- jdk版本: Java8;
- Maven版本: Apache-maven-3.6.2;
- Spring Boot版本: 2.2.1.RELEASE;
- 数据库: Mysql 5.7
- 短信平台:容联云
二、创建Spring Boot项目
这里项目基本已经创建成功,接下来点击Finish自动下载好依赖就可以了
三、创建数据库
- 新建数据库 sms
- 创建表sms_code
CREATE TABLE `sms_code` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`phone` varchar(20) NOT NULL COMMENT '手机号',
`code` varchar(6) NOT NULL COMMENT '验证码',
`expiredTime` datetime NOT NULL COMMENT '过期时间',
`createTime` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb4;
- 创建表sms_user
CREATE TABLE `sms_user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`phone` varchar(25) CHARACTER SET utf8 NOT NULL COMMENT '手机号码',
`loginTime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次登录时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
四、 配置项目基本环境
- 配置application.properties
# 激活哪个环境下的配置
spring.profiles.active=dev
- 配置application-dev.properties
# 端口
server.port=8888
service.ip=127.0.0.1
# 数据库配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/sms?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT&zeroDateTimeBehavior=round
# 数据库账号
spring.datasource.username=root
# 数据库密码
spring.datasource.password=123456
# mybatis plus 设置
mybatis-plus.mapper-locations=classpath:/mapper
- 创建短信配置文件systemConfig-dev.properties
# 短信配置
system.sms.serverIp=app.xxx
system.sms.serverPort=88xx
system.sms.accountSid=8a48bxxx
system.sms.authToken=011xxx
system.sms.appId=8axxxx
system.sms.securityCodeTemplate=26xxxx
- 文件位置
五、具体代码
model代码
- smsUser代码
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
import lombok.ToString;
@Data
@TableName("sms_user")
public class SmsUser implements Serializable {
private Long id;
private String phone;
private Date loginTime;
}
- smsCode代码
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableName;
import lombok.Data;
@Data
@TableName("sms_code")
public class SmsCode implements Serializable {
private Long id;
private String phone;
private String code;
private Date expiredTime;
private Date createTime;
}
接口代码
import com.duoduo.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/login")
public class ApiSmsLoginController {
@Autowired
private SmsService smsService;
@PostMapping("/sendLoginSms")
public void sendLoginSms(@RequestParam String phone){
smsService.sendLoginSms(phone);
}
}
逻辑层代码
import cn.hutool.core.util.RandomUtil;
import com.duoduo.sms.util.SMSUtil;
import com.duoduo.sms.dao.SmsCodeDao;
import com.duoduo.sms.model.SmsCode;
import com.duoduo.sms.model.SmsUser;
import com.duoduo.sms.service.SmsService;
import com.duoduo.sms.service.SmsUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Date;
@Service
public class SmsServiceImpl implements SmsService {
private Logger logger= LoggerFactory.getLogger(this.getClass());
@Autowired
private SmsUserService smsUserService;
@Autowired
private SmsCodeDao smsCodeDao;
@Autowired
private SMSUtil sms;
@Override
public void sendLoginSms(String phone) {
SmsUser smsUser = smsUserService.selectByPhone(phone);
if (StringUtils.isEmpty(smsUser)){
throw new RuntimeException("手机号码不存在");
}
String code= RandomUtil.randomNumbers(6);
querySmsCode(phone,code);
logger.info("手机号{}的验证码为:{}",phone,code);
try {
sms.sendMessage(phone,sms.getSecurityCodeTemplate(),new String[]{code});
} catch (Exception e) {
logger.error("发送验证码失败",e);
throw new RuntimeException("发送验证码失败");
}
}
private void querySmsCode(String phone,String code) {
SmsCode smsCode=new SmsCode();
smsCode.setPhone(phone);
smsCode = smsCodeDao.selectOne(smsCode);
if (StringUtils.isEmpty(smsCode)){
smsCode=new SmsCode();
smsCode.setPhone(phone);
smsCode.setCode(code);
smsCode.setCreateTime(new Date());
smsCode.setExpiredTime(SMSUtil.getExpiredTime());
smsCodeDao.insert(smsCode);
}else {
smsCode.setCode(code);
smsCode.setExpiredTime(SMSUtil.getExpiredTime());
smsCode.setCreateTime(new Date());
smsCodeDao.updateById(smsCode);
}
}
}
@Service
public class SmsUserServiceImpl implements SmsUserService {
@Autowired
private SmsUserDao smsUserDao;
@Override
public SmsUser selectByPhone(String phone) {
SmsUser smsUser=new SmsUser();
smsUser.setPhone(phone);
return smsUserDao.selectOne(smsUser);
}
}
Dao代码
@Repository
public interface SmsUserDao extends BaseMapper<SmsUser> {
}
@Repository
public interface SmsCodeDao extends BaseMapper<SmsCode> {
}
六、项目结构图
项目下载地址
欢迎留言评论,谢谢!