1.需要到阿里云开通模板管理和签名管理,截图如下:
2.导入maven依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> </dependency>
3.application.properties
# 服务端口 server.port=8005 # 服务名 spring.application.name=service-msm spring.redis.host=192.168.10.100 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 #最小空闲 #返回json的全局时间格式 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 #mybatis日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl # nacos服务地址 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
4.utils
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]) + " "); } System.out.print(" "); return r; } }
5.启动类
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class ServiceMsmApplication { public static void main(String[] args) { SpringApplication.run(ServiceMsmApplication.class, args); } }
6.controller
@RestController @RequestMapping("/edumsm/msm") @CrossOrigin public class MsmController { @Autowired private MsmService msmService; @Autowired private RedisTemplate<String,String> redisTemplate; //发送短信的方法 @GetMapping("send/{phone}") public R sendMsm(@PathVariable String phone) { //1 从redis获取验证码,如果获取到直接返回 String code = redisTemplate.opsForValue().get(phone); if(!StringUtils.isEmpty(code)) { return R.ok(); } //2 如果redis获取 不到,进行阿里云发送 //生成随机值,传递阿里云进行发送 code = RandomUtil.getFourBitRandom(); 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("短信发送失败"); } } }
7.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", "LTAI4GDTqjJkxrB353q44ejE", "rdy8GeTHEYeKOGrY1EJ8pKGdQodMSv"); 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","SMS_189617902"); //申请阿里云 模板code request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据,转换json数据传递 try { //最终发送 CommonResponse response = client.getCommonResponse(request); boolean success = response.getHttpResponse().isSuccess(); return success; }catch(Exception e) { e.printStackTrace(); return false; } } }