阿里云和腾讯云短信服务需要注册,可以使用容联云无需注册,供我们学习使用和测试

容联云网址,注册登录后有免费的8块钱额度yuntongxun.comicon-default.png?t=M276https://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)icon-default.png?t=M276http://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测试:填入手机号

 

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值