思维导图
-
第一步
自己开通阿里云的短信服务,并注册签名和模板,了解费用等 -
第二步
导入使用阿里云短信服务的依赖,fastjson是转json工具,后面要使用
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
- 第三步
在application.properties配置上redis,并开启redis服务
#redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
- 第四步
创建controller(R为统一返回数据类型,用于前后端交互数据的统一,就是个人定义的)
@RestController
@CrossOrigin
@RequestMapping("/msm")
public class MsmApiController {
@Autowired private MsmService msmService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
// 发送短信的方法
@GetMapping("send/{phone}")
public R sendMsm(@PathVariable String phone) {
//1.从缓存里取验证码,如果有直接返回
String code = redisTemplate.opsForValue().get(phone);
if(!StringUtils.isEmpty(code)){
return R.ok();
}
// 生成随机值,传递阿里云进行发送
code = RandomUtil.getSixBitRandom();
Map<String, Object> param = new HashMap<>();
param.put("code", code);
// 调用service发送短信的方法
boolean isSend = msmService.send(param, phone);
if(isSend) {
//发送成功后把验证码放入redis
//设置有效时间
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return R.ok();
} else {
return R.error().message("短信发送失败");
}
}
}
RandomUtils工具类(用于随机生成验证码数据,阿里云只帮忙发送,不帮忙生成验证码)
public class RandomUtil {
private static final Random random = new Random();
private static final DecimalFormat fourdf = new DecimalFormat("0000");
private static final DecimalFormat sixdf = new DecimalFormat("000000");
//四位验证码
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
//六位验证码
public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}
/**
* 给定数组,抽取n个数据
* @param list
* @param n
* @return
*/
public static ArrayList getRandom(List list, int n) {
Random random = new Random();
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
// 生成随机数字并存入HashMap
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
// 从HashMap导入数组
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
// 遍历数组并打印数据
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
- 第五步
创建service的实现类
@Service
public class MsmServiceImpl implements MsmService {
@Override
public boolean send(Map<String, Object> param, String phone) {
if(StringUtils.isEmpty(phone))return false;
DefaultProfile profile=
DefaultProfile.getProfile("default", "阿里云的accesskeyid", "key对应的密码");
IAcsClient client=new DefaultAcsClient(profile);
//设置相关参数 固定的
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
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", "申请阿里云 模板code"); //申请阿里云 模板code
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据,转换json数据传递
//最终发送
try {
CommonResponse commonResponse = client.getCommonResponse(request);
boolean success = commonResponse.getHttpResponse().isSuccess();
return success;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}