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/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
mybatis-plus.type-aliases-package=com.duoduo.sms.model
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
mybatis-plus.global-config.id-type=0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
mybatis-plus.global-config.field-strategy=1
#刷新mapper 调试神器
mybatis-plus.global-config.refresh-mapper=true
#逻辑删除配置
mybatis-plus.global-config.logic-delete-value=0
mybatis-plus.global-config.logic-not-delete-value=1
mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector
mybatis-plus.configuration.cache-enabled=false
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#打印出sql语句
logging.level.com.hxsj.inspection.commondb.dao=DEBUG
debug=true
- 创建短信配置文件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;
/**
* @author duoduo
* @date 2019-12-04 18:21:22
* @email cduolai@163.com
*/
@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;
/**
* @author duoduo
* @date 2019-12-04 18:21:22
* @email cduolai@163.com
*/
@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;
/**
* @ClassName: ApiSmsLoginController
* @program: sms->ApiSmsLoginController
* @Description: 短信验证码登录接口
* @author: duolai
* @create: 2019-12-04 18:27
**/
@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;
/**
* @ClassName: SmsServiceImpl
* @program: sms->SmsServiceImpl
* @Description: 发送短信验证码实现类
* @author: duolai
* @create: 2019-12-04 18:30
**/
@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;
/**
* 发送登录验证短信
*
* @param phone
*/
@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("发送验证码失败");
}
}
/**
* @Description: 查询并更新数据库验证码信息
* @Param: [phone, code]
* @Author: duolai
* @Date: 2019/12/4
* @return: void
*/
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;
/**
* 查询账号是否存存在
*
* @param phone
*/
@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> {
}
六、项目结构图
项目下载地址
欢迎留言评论,谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/159029.html