# SpringBoot_sms **Repository Path**: CYSpringBoot/SpringBoot_sms ## Basic Information - **Project Name**: SpringBoot_sms - **Description**: 阿里云短信服务 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2019-07-09 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SpringBoot_sms #### 介绍 > SpringBoot_Redis_阿里云短信服务 #### Redis环境配置 - Redis环境搭建
使用docker搭建Redis,可以参照[菜鸟教程](https://www.runoob.com/docker/docker-install-redis.html)中的方式搭建 - 使用rdm工具可以查看Redis中存储内容 ![Redis](https://images.gitee.com/uploads/images/2019/0709/145540_24aa908f_4776933.png) #### SpringBoot项目配置Redis - pom文件依赖 ```xml org.springframework.boot spring-boot-starter-data-redis ``` - application.properties 文件配置 ```properties # redis spring.redis.host = 127.0.0.1 ## Redis服务器连接端口 spring.redis.port=6379 ## 连接超时时间(毫秒) spring.redis.timeout=5000 ## Redis服务器连接密码(默认为空) spring.redis.password= ## 连接池中的最大连接数 spring.redis.poolMaxTotal=10 ## 连接池中的最大空闲连接 spring.redis.poolMaxIdle=10 ## 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.poolMaxWait=3 ``` - Redis工具类封装 ```java public interface RedisService { // Redis设置值 public void set(String key,String value); // Redis设置值并设置过期时间 public void set(String key,String value,int timeout); // Redis获取key对应的值 public String get(String key); // Redis删除key对应的值 public void del(String key); } ``` ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service public class RedisServiceImpl implements RedisService { @Autowired private StringRedisTemplate template; @Override public void set(String key, String value) { ValueOperations operations = template.opsForValue(); operations.set(key,value); } @Override public void set(String key, String value, int timeout) { ValueOperations operations = template.opsForValue(); operations.set(key,value, timeout, TimeUnit.SECONDS); } @Override public String get(String key) { ValueOperations operations = template.opsForValue(); return operations.get(key); } @Override public void del(String key) { template.delete(key); } } ``` > 至此Redis配置完成 #### 阿里巴巴短信服务接入 > 可以参照阿里巴巴短信服务接入文档接入,这里直接介绍如何使用 - pom文件依赖 ``` xml com.aliyun aliyun-java-sdk-core 4.1.0 com.alibaba fastjson 1.2.38 ``` - 阿狸巴巴短信服务使用步骤 1. 申请 [accessKeyId 和 accessKeySecret](https://dysms.console.aliyun.com/dysms.htm)(如果没有注册用户,自行创建用户) 2. 注册 [短信签名](https://dysms.console.aliyun.com/dysms.htm#/domestic/text/sign) 3. 申请 [短信模板](https://dysms.console.aliyun.com/dysms.htm#/domestic/text/template) - 调用阿里巴巴短信接口发送短信 ```java import com.lcy.springboot_sms.Exception.ResultData; public interface SMSService { // 发送短信 public ResultData sendSms(String moblie); // 验证用户验证码 public ResultData checkSms(String moblie, String code); } ``` ````java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.utils.StringUtils; import com.lcy.springboot_sms.Const.Constant; import com.lcy.springboot_sms.Enum.ResultEnum; import com.lcy.springboot_sms.Exception.DataException; import com.lcy.springboot_sms.Exception.ResultData; import com.lcy.springboot_sms.Utils.IdentifyCodeUtils; import com.lcy.springboot_sms.Utils.ResultUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class SMSServiceImpl implements SMSService { @Autowired private RedisService redisService; @Override public ResultData sendSms(String mobile) { String idCode; //1. 判断是否缓存该账号验证码 String returnCode = redisService.get(mobile + Constant.smsLoginID); if (returnCode != null) { // 如果returnCode存在直接使用 idCode = returnCode; } else { // 生成6位短信验证码 idCode = IdentifyCodeUtils.getCode(); } Map codeMap = new HashMap<>(); codeMap.put("code", idCode); // 使用阿里云短信框架发送短信 DefaultProfile profile = DefaultProfile.getProfile("default", Constant.accessKeyId, Constant.accessKeySecret); IAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); request.setMethod(MethodType.POST); request.setDomain(Constant.accessKeyDoMain); request.setVersion("2017-05-25"); // 发送短信接口名 request.setAction("SendSms"); request.putQueryParameter("PhoneNumbers", mobile); // 短信签名名称 申请完成短信签名 request.putQueryParameter("SignName", "随行"); // 模板ID 短信模板创建完成后,会自带模板ID,阿里短信平台控制台 request.putQueryParameter("TemplateCode", "SMS_169899524"); // 短信模板中的变量参数 request.putQueryParameter("TemplateParam", "{\"code\":\"" + idCode + "\"}"); try { CommonResponse response = client.getCommonResponse(request); JSONObject object = JSON.parseObject(response.getData()); System.out.println(response); //短信发送成功后存入redis if (response != null && Constant.smsOK.equalsIgnoreCase((String) object.get("Message")) && StringUtils.isEmpty(returnCode)) { // code 缓存15分钟 redisService.set(mobile + Constant.smsLoginID, idCode, 900); return ResultUtils.success(); } throw new DataException(ResultEnum.SEND_SMS_FAILURE); } catch (ServerException e) { throw new DataException(new Integer(e.getErrCode()),e.getErrMsg()); } catch (ClientException e) { throw new DataException(new Integer(e.getErrCode()),e.getErrMsg()); } } @Override public ResultData checkSms(String mobile, String code) { if (StringUtils.isEmpty(mobile) ){ throw new DataException(ResultEnum.PHONE_NULL); } if (StringUtils.isEmpty(code)) { throw new DataException(ResultEnum.CODE_NULL); } String returnCode = redisService.get(mobile + Constant.smsLoginID); if (!StringUtils.isEmpty(returnCode) && returnCode.equals(code)) { // 验证成功, 删除redis. redisService.del(mobile + Constant.smsLoginID); // 返回信息 return ResultUtils.info(ResultEnum.CODE_RIGHT); } throw new DataException(ResultEnum.CODE_ERROR); } } ```` - Controller ```java import com.lcy.springboot_sms.Service.SMSService; import com.lcy.springboot_sms.Exception.ResultData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SMSController { @Autowired private SMSService smsService; @PostMapping(value = "sendSms") public ResultData sendSms(String phoneNo) { return smsService.sendSms(phoneNo); } @PostMapping(value = "checkSms") public ResultData checkSms(String phoneNo, String code) { return smsService.checkSms(phoneNo,code); } } ``` #### 接口测试 - 发送短信
![sendSMS](https://images.gitee.com/uploads/images/2019/0709/145733_37ba890b_4776933.png) - 验证短信验证码
![checkSms](https://images.gitee.com/uploads/images/2019/0709/150054_379129b7_4776933.png)