赞
踩
点击登录阿里云短信服务控制台--->点击 添加签名
这里需要注意的时,因为现在阿里云管控的比较严格!!!要求申请之前必须有已经注册备案过的域名网站在使用!!!如果没有,就没必要往下面看了。
点击进来以后,按照要求填写:因为一个账号只能选购一种,所以我这里就没法仔细演示了。
添加完成之后,等待审核!!!!一般2个小时就会出来审核结果了,这里我因为注册申请时填写规则有误,足足审核了7次才通过!!!!!
二:模板管理
点击添加模板:
然后点击添加即可,一把2-3个小时就可以申请出结果了。
三:获取用户AccessKey
点击 继续使用AccessKey
点击完成之后,点击图片中的创建AccessKey 将生成的 AccessKey 保存下来!
四:在项目代码中引入阿里云依赖, 根据你需要的版本不同,自己引入。我这里引入的可以作为参考
1:修配置文件
- <dependencies>
- <dependency>
- <groupId>com.aliyun</groupId>
- <artifactId>aliyun-java-sdk-core</artifactId>
- </dependency>
- </dependencies>
2、添加配置文件application.properties 将下面的服务地址改为自己对应的地址
- # 服务端口
- server.port=8204
- # 服务名
- spring.application.name=service-msm
-
- #返回json的全局时间格式
- spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
- spring.jackson.time-zone=GMT+8
-
- spring.redis.host=192.168.44.165
- 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
-
- # nacos服务地址
- spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
-
- aliyun.sms.regionId=default
- aliyun.sms.accessKeyId=LT6I0Y5633pX89qC
- aliyun.sms.secret=jX8D04Dm12I3gGKj345FYSzu0fq8mT
3:创建一个SpringBoot 启动类
- @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
- @EnableDiscoveryClient
- public class ServiceMsmApplication {
- public static void main(String[] args) {
- SpringApplication.run(ServiceMsmApplication.class, args);
- }
- }
-
-
- /因为没有在配置文件中配置数据库的信息,害怕报错,所以取消数据源自动自动配置
4:添加一个配置工具类类
- @Component
- public class ConstantPropertiesUtils implements InitializingBean {
-
- //InitializingBean 初始化bean 让spring 容器一初始化就加载
- @Value("${aliyun.sms.regionId}")
- private String regionId;
-
- @Value("${aliyun.sms.accessKeyId}")
- private String accessKeyId;
-
- @Value("${aliyun.sms.secret}")
- private String secret;
-
- public static String REGION_Id;
- public static String ACCESS_KEY_ID;
- public static String SECRECT;
-
- @Override
- public void afterPropertiesSet() throws Exception {
- REGION_Id=regionId;
- ACCESS_KEY_ID=accessKeyId;
- SECRECT=secret;
- }
- }
在项目中编写:
MsmApiController:
- package com.hospital.controller;
-
- import com.hospital.common.result.Result;
- import com.hospital.service.MsmService;
- import com.hospital.utils.RandomUtil;
- import io.swagger.annotations.ApiOperation;
- 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.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.concurrent.TimeUnit;
-
- @RestController
- @RequestMapping("/api/msm")
- @SuppressWarnings("ALL")
- public class MsmApiController {
- @Autowired
- private MsmService msmService;
-
- @Autowired
- private RedisTemplate<String,String> redisTemplate;
-
- //将手机验证码存放到redis 中,并设置过期时间
- @ApiOperation(value = "发送手机验证码")
- @GetMapping("send/{phone}")
- public Result sendCode(@PathVariable(required = true) String phone){
- // phone 作为redis 中的key, code 作为redis 中的value值
- String code = redisTemplate.opsForValue().get(phone);
- if (!StringUtils.isEmpty(code)) {
- //这里为什么从redis 拿取 验证码 我理解的是 ,因为redis 验证码我们给他设置了时间限制,所以在规定时间内,验证码
- //可以多次使用,一旦时间到期之后,我们就需要从新生成6位数的验证码了。
- return Result.ok();
- }
- //生成六位验证码
- code = RandomUtil.getSixBitRandom();
- //调用service 方法,整合阿里云短信服务进行发送
- Boolean isSend = msmService.send(phone,code);
- //返回的Boolean 值进行判断 ,如果发送信息成功,即存入到redis 中,如果没有则提示验证码发送失败
- if (isSend) {
- //放到redis中规定时间内有效
- redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
- return Result.ok();
- } else {
- return Result.fail().message("发送短信失败!请重新发送");
- }
- }
- }
MsmService
- @Service
- public interface MsmService {
- Boolean send(String phone, String code);
- }
MsmServiceImpl
- package com.hospital.service.impl;
-
- 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.hospital.service.MsmService;
- import com.hospital.utils.ConstantPropertiesUtils;
- import org.springframework.stereotype.Service;
- import org.springframework.util.StringUtils;
-
- import java.util.HashMap;
- import java.util.Map;
-
- @Service
- public class MsmServiceImpl implements MsmService {
- //根据手机号,存入验证码
- @Override
- public Boolean send(String phone, String code) {
- //判断手机号是否为空
- if (StringUtils.isEmpty(phone)) {
- return false;
- }
- //整合阿里云的短信服务
- 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");
- request.setAction("SendSms");
- // request.setSysAction();
-
- //手机号
- request.putQueryParameter("PhoneNumbers", phone);
- //签名名称
- request.putQueryParameter("SignName", "自己申请的短信签名");
- //模板code
- request.putQueryParameter("TemplateCode", "短信模板CODE");
- //验证码 使用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);
- System.out.println(response.getData());
- return response.getHttpResponse().isSuccess();
- } catch (ServerException e) {
- e.printStackTrace();
- } catch (ClientException e) {
- e.printStackTrace();
- }
- return false;
- }
- }
ConstantPropertiesUtils 工具类
- @Component
- public class ConstantPropertiesUtils implements InitializingBean {
-
- //InitializingBean 初始化bean 让spring 容器一初始化就加载
- @Value("${aliyun.sms.regionId}")
- private String regionId;
-
- @Value("${aliyun.sms.accessKeyId}")
- private String accessKeyId;
-
- @Value("${aliyun.sms.secret}")
- private String secret;
-
- public static String REGION_Id;
- public static String ACCESS_KEY_ID;
- public static String SECRECT;
-
- @Override
- public void afterPropertiesSet() throws Exception {
- REGION_Id=regionId;
- ACCESS_KEY_ID=accessKeyId;
- SECRECT=secret;
- }
RandomUtil 工具类
- 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;
- }
- }
开启启动类调接口测试
- @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
- @EnableDiscoveryClient
- @ComponentScan(basePackages = {""})
- public class ServiceMsmApplication {
- public static void main(String[] args) {
- SpringApplication.run(ServiceMsmApplication.class, args);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。