容联云网址,注册登录后有免费的8块钱额度yuntongxun.comhttps://www.yuntongxun.com/member/main
在控制台首页处注意以下几个内容,后面要用到
然后在测试号码处,添加测试号码
接下来就是在idea
1 添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
2 配置文件:容联云配置accountSId,accountToken,appId,就是文章开头的三个红框的值
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.164.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
# nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#容联云配置
app.cloopen.accountSId=1
app.cloopen.accountToken=1
app.cloopen.appId=1
app.cloopen.restDevUrl=https://app.cloopen.com
3 启动类:因为没有用到数据库,所以要取消数据源配置
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
@EnableDiscoveryClient
public class ServiceMsmApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceMsmApplication.class, args);
}
}
4 封装两个工具类
一个是生成4或者6位随机验证码
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;
}
}
一个是调用配置文件的容联云账户信息
@Component
public class ConstantPropertiesUtils implements InitializingBean {
@Value("${app.cloopen.accountSId}")
private String accountSId;
@Value("${app.cloopen.accountToken}")
private String accountToken;
@Value("${app.cloopen.appId}")
private String appId;
@Value("${app.cloopen.restDevUrl}")
private String restDevUrl;
/**
* 定义三个常量属性对外暴露调用
*/
public static String ACCOUNTS_ID;
public static String ACCOUNT_TOKEN;
public static String APP_ID;
public static String REST_DEV_URL;
/**
* 加载执行的方法
* 对三个变量赋值
*
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
ACCOUNTS_ID = accountSId;
ACCOUNT_TOKEN = accountToken;
APP_ID = appId;
REST_DEV_URL = restDevUrl;
}
}
5 controller
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
@Resource
private MsmApiService msmApiService;
@Resource
private RedisTemplate<String,String> redisTemplate;
//发送手机验证码
@GetMapping("send/{phone}")
public Result sendCode(@PathVariable("phone") String phone) {
//从redis获取验证码,如果获取获取到,返回ok
// key 手机号 value 验证码
String code = redisTemplate.opsForValue().get(phone);
if(!StringUtils.isEmpty(code)) {
return Result.ok();
}
//如果从redis获取不到,
// 生成验证码,生成6位验证码
code = RandomUtil.getSixBitRandom();
//调用service方法,通过整合短信服务进行发送
boolean isSend = msmApiService.send(phone,code);
//生成验证码放到redis里面,设置有效时间
if(isSend) {
redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
return Result.ok();
} else {
return Result.fail().message("发送短信失败");
}
}
}
6 service接口 和serviceimpl业务实现类
业务实现类可以参考容联云的DEMO文档Demo示例 (yuntongxun.com)http://doc.yuntongxun.com/p/5a533e0c3b8496dd00dce08c
public interface MsmApiService {
//发送手机验证码
boolean send(String phone, String code);
}
@Service
public class MsmApiServiceImpl implements MsmApiService {
//发送手机验证码
@Override
public boolean send(String phone, String code) {
//判断手机号是否为空
if (StringUtils.isEmpty(phone)) {
return false;
}
// 整合容联云发送短信
//生产环境请求地址:app.cloopen.com
String serverIp = "app.cloopen.com";
//请求端口
String serverPort = "8883";
//主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
String accountSId = ConstantPropertiesUtils.ACCOUNTS_ID;
String accountToken = ConstantPropertiesUtils.ACCOUNT_TOKEN;
//请使用管理控制台中已创建应用的APPID
String appId = ConstantPropertiesUtils.APP_ID;
CCPRestSmsSDK sdk = new CCPRestSmsSDK();
sdk.init(serverIp, serverPort);
sdk.setAccount(accountSId, accountToken);
sdk.setAppId(appId);
sdk.setBodyType(BodyType.Type_JSON);
String to = phone;
//短信模板
String templateId = "1";
//验证码为生成的随机数,2分钟内到期
String[] datas = {code, "2"};
HashMap<String, Object> result = sdk.sendTemplateSMS(to, templateId, datas);
if ("000000".equals(result.get("statusCode"))) {
//正常返回输出data包体信息(map)
HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
Set<String> keySet = data.keySet();
for (String key : keySet) {
Object object = data.get(key);
System.out.println(key + " = " + object);
}
return true;
} else {
//异常返回输出错误码和错误信息
System.out.println("错误码=" + result.get("statusCode") + " 错误信息= " + result.get("statusMsg"));
return false;
}
}
}
7 使用swagger测试:填入手机号