1、说明*
- 本例仅仅是一个短信发送的demo,并不包含登录时双重验证、加密加盐以及权限设计等等,仅作参考
2、创建项目前的准备工作
2.1、创建阿里云账户
- 随后点击AccessKey管理
- 我的阿里云无所谓,随便整,权限给足,就怕没权限给报错了😤
2.2、开通SMS短信服务
- 如图所示:
- 注意:新用户开通会有100条,用完就只有花钱,所以做测试能省则省🙃
- 绑定完手机号,可以先在控制台测试一下,建议就用阿里提供的测试模板和签名,因为申请都会进行人工审核,太慢了,还不太容易通过
- 这个测试没问题,就直接进行下一步了,选中API发送测试,使用测试模板,点击调用,会跳到详情界面
- 如上图所示:
- 第一步先找到SDK信息,导入maven依赖
- 这几个响应参数,后面做验证可能用到
3、部分代码截图和运行效果
- 短信发送请求
- 处理登录请求
- 页面
- 短信发送成功
- 手机接收短信
- 存入redis成功
4、主要工具类以及配置类
- spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- redis连接池配置-->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<property name="maxIdle" value="10"/>
<!--连接池的最大数据库连接数 -->
<property name="maxTotal" value="1000"/>
<!--最大建立连接等待时间-->
<property name="maxWaitMillis" value="-1"/>
</bean>
<!--redis连接工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
destroy-method="destroy">
<property name="poolConfig" ref="jedisPoolConfig"></property>
<!--IP地址 -->
<property name="hostName" value="localhost"></property>
<!--端口号 -->
<property name="port" value="6379"></property>
<!--客户端超时时间单位是毫秒 -->
<property name="timeout" value="2000"></property>
</bean>
<!--redis操作模版,使用该对象可以操作redis。 StringRedisSerializer决定编码 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
<!--根据需求可自行选择加入-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
</bean>
<!--对工具类赋值-->
<bean id="redisUtils" class="com.llh.utils.RedisUtils">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
</beans>
- AlyUtils.java
package com.llh.utils;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
public class AlyUtils {
public static final String ACCESS_KEY_ID = "LTAI5t8M6dewZALaTRb3QEC7";
public static final String ACCESS_KEY_SECRET = "9iG7iCRwATM0cVB8kPxmPSTbhqotqk";
// 接受短信的手机号码
public static final String PhoneNumbers = "17780255297";
// 短信签名名称
public static final String SignName = "阿里云短信测试";
// 短信模板code
public static final String TemplateCode = "SMS_154950909";
// 短信模板变量对应的实际值(如果JSON中需要带换行符,请参照标准的JSON协议处理)
public static final String TemplateParam = "{\"code\":\"1234\"}";
/**
* 自定义发送短信方法
* @param phoneNumbers 传入的手机号
* @param templateParam 自定义模板的参数值
* @return SendSmsResponseBody
* @throws Exception
*/
public static SendSmsResponseBody sendSms(String phoneNumbers, String templateParam) throws Exception {
Client client = AlyUtils.createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
SendSmsRequest request = new SendSmsRequest();
request.setSignName(SignName);
request.setTemplateCode(TemplateCode);
request.setPhoneNumbers(phoneNumbers);
request.setTemplateParam(templateParam);
RuntimeOptions runtime = new RuntimeOptions();
SendSmsResponse smsResponse = client.sendSmsWithOptions(request, runtime);
return smsResponse.getBody();
}
/**
* 使用AK&SK初始化账号Client
*
* @param accessKeyId 阿里云账户 ACCESS_KEY_ID
* @param accessKeySecret 阿里云账户 ACCESS_KEY_SECRET
* @return Client
* @throws Exception
*/
public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
// 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
Client client = AlyUtils.createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
SendSmsRequest sendSmsRequest = new SendSmsRequest();
sendSmsRequest.setPhoneNumbers(PhoneNumbers);
sendSmsRequest.setSignName(SignName);
sendSmsRequest.setTemplateCode(TemplateCode);
sendSmsRequest.setTemplateParam(TemplateParam);
RuntimeOptions runtime = new RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
client.sendSmsWithOptions(sendSmsRequest, runtime);
SendSmsResponseBody sendSms = AlyUtils.sendSms(AlyUtils.PhoneNumbers, AlyUtils.TemplateParam);
System.out.println(sendSms.getCode());
// bizId = 193407486023040709^0
// code = ok
// message = ok
// requestId = BB3D1DB4-2ECF-5888-B190-07A8451FED4E
} catch (TeaException error) {
// 如有需要,请打印 error
String s = Common.assertAsString(error.message);
System.out.println(s);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 如有需要,请打印 error
String s = Common.assertAsString(error.message);
System.out.println(s);
}
}
}
- RedisUtils.java
package com.llh.utils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.CollectionUtils;
import java.util.concurrent.TimeUnit;
public class RedisUtils {
private static RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate) {
//根据需要加入
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
this.redisTemplate = redisTemplate;
}
//=============================common============================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public static Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public static boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public static boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
59 comments
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合 的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合 的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合 的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
罗宾汉也疯狂
碧血剑
红鬼仔
哈里福音
金太狼的幸福生活
红颜
爱情诅咒
矛盾修饰法
环游地球八十天
长江7号超萌特攻队
雨和你的故事
好人寥寥
奇袭地道战