pom.xml
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.10</version>
</dependency>
application.properties
# 服务端口
server.port=8007
aliyun.oss.file.keyid=LTAI5tF6XBBDBh6KAYjPdwtj
aliyun.oss.file.keysecret=ZwOd2NAOVTHipXyKITcJeBHGBpRMZw
#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#redis
spring.redis.host=192.168.139.128
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
随机生成数字
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;
}
}
短信业务
@Service
public class MsmServiceImpl implements MsmService {
@Autowired
private RedisTemplate<String,String> redisTemplate;//使用redis
@Override
public boolean sendsms(String phone) {
String redis = redisTemplate.opsForValue().get(phone);
if (!StringUtils.isEmpty(redis)){//判断有没有验证码
return true; }
Config config = new Config()
.setAccessKeyId(PropertiesUtils.ACCESS_KEY_ID) // 您的 AccessKey ID
.setAccessKeySecret(PropertiesUtils.ACCESS_KEY_SECRET); // 您的 AccessKey Secret
config.endpoint = "dysmsapi.aliyuncs.com"; // 访问的域名
Map<String,String> map=new HashMap<>();
String code=RandomUtil.getFourBitRandom();//随机生成数字
map.put("code",code);
try {
com.aliyun.dysmsapi20170525.Client client= new com.aliyun.dysmsapi20170525.Client(config);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)//手机号
.setSignName("阿里云短信测试")//签名
//模板
.setTemplateCode("SMS_154950909")
//验证码json格式{code:1234}
.setTemplateParam(JSONObject.toJSONString(map));
RuntimeOptions runtime = new RuntimeOptions();
SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
if(sendSmsResponse.getBody().getCode().equals("OK")){
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//设置redis时间5分钟
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}