文章目录
最好有SpringBoot的基础!!!
通过Springboot构建项目,并整合短信服务,将验证码存入redis中并设置过期时间。
开通阿里云
了解阿里云用户权限操作
链接:阿里云官网
1、注册账户进行登录
2、点击AccessKey管理,开通使用子用户AccessKey
3、添加用户
4、添加对应的账号的权限
对应的权限举例:
- 管理对象存储服务(OSS)权限
- 管理短信服务(SMS)权限
- 管理视频点播服务(VOD)权限
5、最后得到AccessKey(ID,密码)
注意一定要保存好信息
开通阿里云短信服务
1、搜索框中搜索短信服务
首先我们先要开通短信服务,我这里已经开通过了所以直接进入控制台。
2、申请模板和签名
在国内消息中添加模板和添加签名
文档:阿里巴巴短信服务文档说明
添加短信模板
1、短信的具体内容
如:您的验证码是:${code},请在5分钟内使用,请勿泄露给被人使用。
2、等待审核通过(需要正当的理由)
添加签名
1、公司的名称
如:【淘宝网】
2、等待审核通过(需要正当的理由)
Springboot整合短信到项目中
1.创建一个SpringBoot的项目
2. 导入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--阿里云短信-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
3. 配置文件
# 应用服务 WEB 访问端口
server.port=8080
# redis配置
spring.redis.host=127.0.0.1
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
# 阿里云短信配置
aliyun.sms.regionId=xxxxxxx
aliyun.sms.accessKeyId=xxxxxxx
aliyun.sms.secret=xxxxxxx
aliyun.sms.signName=xxxxxxx
aliyun.sms.templateCode=xxxxxxx
4. 主启动类
@EnableSwagger2
@ComponentScan(basePackages = {"com.siro"})
@SpringBootApplication
public class MsmTestApplication {
public static void main(String[] args) {
SpringApplication.run(MsmTestApplication.class, args);
}
}
5. 工具类
public class RandomUtil {
private static final Random random = new Random();
private static final DecimalFormat fourdf = new DecimalFormat("0000");
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
}
@Component
public class ConstantPropertiesUtils implements InitializingBean {
@Value("${aliyun.sms.regionId}")
private String regionId;
@Value("${aliyun.sms.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.sms.secret}")
private String secret;
@Value("${aliyun.sms.signName}")
private String signName;
@Value("${aliyun.sms.templateCode}")
private String templateCode;
public static String REGION_ID;
public static String ACCESS_KEY_ID;
public static String SECRECT;
public static String SIGN_NAME;
public static String TEMPLATE_CODE;
@Override
public void afterPropertiesSet() throws Exception {
REGION_ID = regionId;
ACCESS_KEY_ID = accessKeyId;
SECRECT = secret;
SIGN_NAME = signName;
TEMPLATE_CODE = templateCode;
}
}
6. 控制器
@Api(description = "短信服务")
@RestController
@RequestMapping("/msm")
public class MsmController {
@Autowired
private MsmService msmService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@ApiOperation(value = "发送短信的方法")
@GetMapping("/send/{phone}")
public Boolean sendMsm(@PathVariable String phone) {
//从redis中获取验证码,如果获取到就直接返回
String code = redisTemplate.opsForValue().get(phone);
if (!StringUtils.isEmpty(code)) {
return true;
}
//如果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 true;
} else {
return false;
}
}
}
7. 业务层
public interface MsmService {
public boolean send(Map<String, Object> param, String phone);
}
@Service
public class MsmServiceIml implements MsmService {
@Override
public boolean send(Map<String, Object> param, String phone) {
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.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
//设置发送相关的参数
request.putQueryParameter("PhoneNumbers", phone); //手机号
request.putQueryParameter("SignName", ConstantPropertiesUtils.SIGN_NAME); //申请阿里云 签名名称
request.putQueryParameter("TemplateCode", ConstantPropertiesUtils.TEMPLATE_CODE); //申请阿里云 模板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;
}
}
}
8. 测试
启动项目,访问swagger地址,输入手机号,点击Try it out!
返回结果是true
,说明发送成功。
查看redis也有对应的验证码。
查看短信也收到了验证码。
如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客