阿里云 短信服务 +SpringBoot+Redis 设置过期时间

以前写了一篇利用阿里云 云市场  买其它公司的服务发短信:https://www.cnblogs.com/mangoubiubiu/p/12860271.html,这篇code是存session里的,用session让 验证码限定过期 

一、申请签名 和模板  ,获取accessKeyId 和secret

1、开通阿里云短信服务

 

2、进入管理控制台申请签名和模板

 

 拿到accessKeyId 和secret

二、代码编写

1、引入依赖

  <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
        </dependency>
    </dependencies>

2、准备生成验证码的工具类

package com.atguigu.msmservice.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 *
 */
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;
    }
}

3、Controller

package com.atguigu.msmservice.controller;


import com.atguigu.msmservice.service.MsmService;
import com.atguigu.commonutils.R;
import com.atguigu.msmservice.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("send/{phone}")
    public R sendPhoneMsg(@PathVariable String phone){

        String code=redisTemplate.opsForValue().get(phone);

        //如果从redis 取值 不为空 代表已经发生短信
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }


        code= RandomUtil.getFourBitRandom();

        Map<String,Object> param=new HashMap<String,Object>();
        param.put("code",code);

        //调用service 发送短信的方法
        Boolean isSend=   msmService.send(param,phone);
         if(isSend){
             //发送成功 后 发验证码 放到 redis 设置 有效时间  key  value   5     分钟
             redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
             return R.ok();
         }else{
             return R.error().message("短信发送失败");
         }
    }


}

4、Service

package com.atguigu.msmservice.service.serviceImpl;

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.atguigu.msmservice.service.MsmService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@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", "你的key", "你的secret");
        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");


        //设置发送相关的参数 注意:key 定死 不能随便写
        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称
        request.putQueryParameter("SignName", "你的模板名");
        request.putQueryParameter("TemplateCode", "你的TemplateCode");
        //传code  将map 转成json
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));


        //最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;

    }
}

4、Swagger UI测试

 

 

 

5、手机端显示 和阿里云控制台 显示

 

 

posted @ 2020-11-14 14:06  KwFruit  阅读(490)  评论(0编辑  收藏  举报