阿里云短信服务学习笔记

阿里云短信服务学习笔记

一、预处理(配置redis,启动redis)

二、controller层

package com.athuiju.msmservice.controller;

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

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

/**
 * @author Ro shinMM
 * @create 2020-08-20 11:05
 */
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {
     
    @Autowired
    private MsmService msmService;
	//redis
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法(注意验证码不是阿里云生成的是我们程序自动生成)
    //阿里云只是得到我们传给它的值,帮我们去发送
    @GetMapping("getCode/{phone}")
    public R getCode(@PathVariable("phone") String phone){
     
        //1 从redis获取验证码,如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
     
            return R.ok();
        }
        //2 如果redis获取不到,进行阿里云发送生成随机值,传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();//随机生成四位数,工具类中
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);
        if (isSend){
     
            //发送成功,把发送成功验证码放到redis里面
            //设置有效时间为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }
        return R.error().message("短信发送失败");
    }
}

三、service层

package com.athuiju.msmservice.service;

import java.util.HashMap; /**
 * @author Ro shinMM
 * @create 2020-08-20 11:13
 */

public interface MsmService {
     
    boolean send(HashMap<String, Object> param, String phone);
}

四、serviceImpl接口层


```java
package com.athuiju.msmservice.service.Impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.athuiju.msmservice.service.MsmService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * @author Ro shinMM
 * @create 2020-08-20 11:15
 */
@Service
public class MsmServiceImpl implements MsmService {
     

    @Override
    public boolean send(HashMap<String, Object> param, String phone) {
     
        if (StringUtils.isEmpty(phone)) return false;
		
		//accessKeyId和accessSecret为阿里云的管理员账号和密码
		//连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("default",
                 "","");
       	//创建客户端
        DefaultAcsClient client = new DefaultAcsClient(profile);
        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone);//手机号
        request.putQueryParameter("SignName","java课程应用"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_199792121");//申请阿里云 模板code
        //验证码数据,我们的param是map格式数据,但是阿里云要的是json数据,所以把map转换成json数据传递
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
     
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();//通过返回值判断短信是否发送成功
        }catch(Exception e) {
     
            e.printStackTrace();
            return false;
        }
    }
}

你可能感兴趣的:(学习)