Bootstrap

Spring Boot+Redis 整合阿里云短信服务

1.登录阿里云


www.aliyun.com

2.产品->短信服务->免费开通


3.国内消息->签名管理->添加签名


4.模板管理->添加模板


5.快速学习->绑定测试手机号


6.主账号->AccessKey管理->申请AccessKey


7.业务层代码规范


@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean sendMessage(String phone, String code) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        //整合aliyun短信服务
        //设置参数
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstantPropertiesUtils.REGION_Id,
                        ConstantPropertiesUtils.ACCESS_KEY_ID,
                        ConstantPropertiesUtils.SECRECT);
        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");//api的版本号是 2017-05-25和当前日期无关
        request.setAction("SendSms");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "我的在线预约挂号系统网站");
        //模板code
        request.putQueryParameter("TemplateCode", "SMS_269235376");
        //验证码  使用json格式   {"code":"123456"}
        Map<String, Object> param = new HashMap();
        //生成验证码
        param.put("code", code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));


        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;

    }
}

8.控制器代码规范


@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    MsmService msmService;

    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //从Redis中获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        //如果获取到 返回ok
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果Redis获取不到
        //生成验证码,整合阿里云短信服务进行发送
        code = RandomUtil.getSixBitRandom();

        boolean isSend = msmService.sendMessage(phone,code);

        //发送短信成功,生成验证码存入Redis,设置有时间为两分钟
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败!");
        }
    }
}

;