前言
将电话以及验证码存入redis,并设置过期时间
一.注册阿里云账号
注册并登录阿里云账号。您可以前往阿里云官方网站(https://www.aliyun.com/),点击右上角的"登录"按钮,然后选择"注册"创建一个新账号或使用已有的账号登录。
二.开通阿里云短信服务
1.在将鼠标移到阿里云首页目录栏的"产品分类"中,这时会弹出许多阿里云产品,我们选择“云通信”类别下的 “短信服务”。如下图:
2. 点击免费开通,新人也可以在首页中点击免费试用,开通三个月一百条短信服务
3.开通后点击国内消息,添加先签名,在添加的签名的基础上添加模板,要使签名和模板连接,添加签名后,两小时内阿里会审核,先等待一会吧
4.开发文档,在首页的文档与社区中
获取AccessKey ID 和 AccessKey Secret ,在阿里云改版后Secret只在第一次申请显示,请妥善保管
application.properties,将上面的AccessKey ID 和 AccessKey Secret 填入其中,我也连接的redis和nacos,将手机号和验证码存入redis
server.port=8120
spring.application.name=service-duanxin
aliyun.sms.regionId=default
aliyun.sms.accessKeyId=XXXXXXXXXXX
aliyun.sms.secret=XXXXXXXXXXXXXX
#???????? redis?
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.timeout=1800000
spring.redis.jedis.pool.max-active=20
spring.redis.jedis.pool.max-wait=1
spring.redis.jedis.pool.max-idle=5
spring.redis.jedis.pool.min-idle=0
#?? ??? mq ????
#?????? nacos?
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
config类 ,在config中一个短信配置类,一个swagger配置类
package com.lizheng.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author 笑起来跟猫似的先生
* @ClassName ConstantPropertiesUtils
* @description: TODO
* @datetime 2023年 08月 02日 16:16
* @version: 1.0
*/
@Component
public class ConstantPropertiesUtils implements InitializingBean {
@Value("${aliyun.sms.regionId}")
private String regionId;//区域
@Value("${aliyun.sms.accessKeyId}")
private String accessKeyId;//短信的key
@Value("${aliyun.sms.secret}")
private String secret;//短信的密钥
public static String REGION_ID;//区域
public static String ACCESS_KEY_ID;//短信的key
public static String SECRET;//短信的密钥
@Override
public void afterPropertiesSet() throws Exception {
REGION_ID=regionId;
ACCESS_KEY_ID=accessKeyId;
SECRET=secret;
}
}
package com.lizheng.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author 笑起来跟猫似的先生
* @ClassName SwaggerConfig
* @description: TODO
* @datetime 2023年 08月 01日 18:46
* @version: 1.0
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket creatRestapi(){
return new Docket(DocumentationType.SWAGGER_2).
pathMapping("/").
select().apis(RequestHandlerSelectors.basePackage("com.lizheng")).
paths(PathSelectors.any()).
build().apiInfo(new ApiInfoBuilder().title("SpringBoot整合Swagger").description("上班用").
version("1.0").contact(new Contact("lizheng","http://www.lizheng.com","lizheng@163.com")).
license("The Apache license").licenseUrl("http://www.lizheng.com").build());
}
}
controller类
package com.lizheng.controller;
import com.lizheng.result.Result;
import com.lizheng.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* @author 笑起来跟猫似的先生
* @ClassName SmsApiController
* @description: TODO
* @datetime 2023年 08月 02日 16:47
* @version: 1.0
*/
@Api(tags = "短信测试")
@RestController
@RequestMapping("/api/sms")
@CrossOrigin //跨域
public class SmsApiController {
@Autowired
private SmsService smsService;
@Autowired
private RedisTemplate<String,String> redisTemplate;
@ApiOperation("发送短信")
@GetMapping("/send/{phone}")
public Result sendCode(@PathVariable String phone){
//code最终随机生成
// 创建一个Random对象
Random random = new Random();
// 生成一个六位随机数
String code = String.valueOf(random.nextInt(900000) + 100000);
// 打印生成的随机数
System.out.println("随机数:" + code);
boolean send = smsService.send(phone,code);
if (send){
redisTemplate.opsForValue().set("duan_xin:"+phone,code,30, TimeUnit.DAYS);
return Result.ok();
}else {
return Result.error().message("发送短信失败");
}
}
}
service
package com.lizheng.service;
import java.util.Map;
/**
* @author 笑起来跟猫似的先生
* @ClassName SmsService
* @description: TODO
* @datetime 2023年 08月 02日 16:48
* @version: 1.0
*/
public interface SmsService {
/**
* 发送短信
* @param phone
* @param code
* @return
*/
public boolean send(String phone,String code);
public boolean send(String phone, String code, Map<String,Object> paramMap);
}
serviceImpl
package com.lizheng.service.impl;
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.profile.DefaultProfile;
import com.google.gson.Gson;
import com.lizheng.config.ConstantPropertiesUtils;
import com.lizheng.service.SmsService;
import io.netty.util.Constant;
import com.aliyuncs.http.MethodType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author 笑起来跟猫似的先生
* @ClassName SmsServiceImpl
* @description: TODO
* @datetime 2023年 08月 02日 16:52
* @version: 1.0
*/
@Service
public class SmsServiceImpl implements SmsService {
@Override
public boolean send(String phone, String code) {
if (StringUtils.isEmpty(phone)){
return false;
}
//设置发短信的参数 整合阿里云短信服务
DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_ID,
ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.SECRET);
/* IAcsClient client = new DefaultAcsClient(profile);
//设置固定参数
CommonRequest request= new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("");*/
//设置发短信人的账户相关参数
//发短信的客户端
IAcsClient client = new DefaultAcsClient(profile);
//设置相关的参数
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
//发送的手机号
request.putQueryParameter("PhoneNumbers",phone);
//签名
request.putQueryParameter("SignName","阿政的信息");
//阿里云的模板[短信模板]
request.putQueryParameter("TemplateCode","SMS_462395064");
//声明map集合
Map<String,Object> param= new HashMap<>();
param.put("code",code);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));//验证码
System.out.println("快成功了");
try {
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
System.out.println("成功");
return success;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
@Override
public boolean send(String phone, String code, Map<String, Object> paramMap) {
if(StringUtils.isEmpty(phone)){
return false;
}
//设置发短信的参数 整合阿里云短信服务
DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_ID,
ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.SECRET);
/* IAcsClient client = new DefaultAcsClient(profile);
//设置固定参数
CommonRequest request= new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("");*/
//设置发短信人的账户相关参数
//发短信的客户端
IAcsClient client = new DefaultAcsClient(profile);
//设置相关的参数
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
//发送的手机号
request.putQueryParameter("PhoneNumbers",phone);
//签名
request.putQueryParameter("SignName","阿政的信息");
//阿里云的模板[短信模板]
request.putQueryParameter("TemplateCode","SMS_282785560");
//声明map集合
/* Map<String,Object> param= new HashMap<>();
param.put("code",code);*/
Gson gson= new Gson();
String jsonParam = gson.toJson(paramMap);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(jsonParam));//验证码
try {
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
return success;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}