Java短信验证码

        想利用java给用户发送短信的话,需要我们与电信、移动、联通三大巨头合作(其实还有广电,但是比较少用),让它帮你发信息,当然直接与它合作显然是不现实的,所以我们要借助第三方的短信平台来替我们发信息。比较有名的短信平台,比如阿里云、腾讯云.....等都可以。短信平台就相当于我们与三大运行商的中介。

1 短信模板

短信模板内容不是随便想写什么就写什么的,每个短信模板都是要由国家工信部进行审核的。

短信模板包含两部分:

  1. 短信签名:【XXXXX】
  2. 短信正文:您的注册短信验证码为:1234

下面是腾讯云给的标准:(短信模板标准)

1、短信签名

签名内容不能含有黄赌毒、宗教和党政等信息。

签名必须能辨别所属公司或个人或者业务信息,不支持中性化签名。例如:xx工作日记、xx的心情、xx语言开发、xx业务测试、xx学习教程、xx个人日记等。即使所申请签名内容与支持的签名类型的名称相同但为中性,亦不支持。

国内短信签名由【】和签名内容组成,格式为【签名内容】。签名内容要求长度为2 - 12个字,由中英文、数字组成,内容不包含【】。 建议国内短信签名内容尽量使用中文。

国际/港澳台短信签名由[]和签名内容组成,格式为[签名内容]。签名内容要求2 - 15个字,内容不包含[]。

2、短信正文

 还有很多细节,大家可以按需自行翻阅文档。

2 开发思路

参考文章:dogbin丶

发送短信是一个比较慢的过程,因为需要用到第三方服务(阿里云短信服务),因此我们使用RabbitMq来做异步处理,前端点击获取验证码后,后端做完校验限流后直接返回发送成功。

发送短信的服务是需要收费的,而且我们也不允许用户恶意刷接口,所以需要有一个接口限流方案。

3 具体实现

至于RabbitMq怎么用,我这边就不再讲解了,因为这部分内容也挺多的,当然不用rabbitmq这类中间件,也完全可以实现短信开发功能,但是不推荐哦,因为这可能导致用户体验不好。(大伙如果不会可以先学学,因为其实RabbitMq用处还是挺多的)。

maven依赖

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>3.0.0</version>
        </dependency>

1、接收短信请求的接口

@RestController
@RequestMapping("/user")
public class UserController {
   
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;

@GetMapping("/getCode")
    public String getCode(String phone){
        String regex="^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
//判断手机号是否合法
        if(Pattern.matches(regex,phone)){
            //判断该手机号一分钟内是否重复提交申请,请求记录保存在redis里面
            String key="SMS::request"+phone;
               //为空说明一分钟内没有请求
           if(redisUtil.getCacheObject(key)==null){
               //将请求记录保存在redisz中,redisUtil是一个工具类
               redisUtil.setCacheObject(key,"",60, TimeUnit.SECONDS);
               //交换机名
               String exchange="user.exchange"; 
                //发送到rabbit交换机中
               rabbitTemplate.convertAndSend(exchange,"",phone);
               return "验证码已发送";
           }else {
               return "一分钟内已申请过验证码,请稍后再申请";
           }
        }else {
            System.out.println("手机号格式不正确!");
            return "手机号格式不正确!";
        }

    }
}

 最终将短信放到rabbit里面等待处理。

user.exchange是一个rabbitmq的交换机

2 rabbit接收发送短信请求

@Component
public class PhoneCodeController {
    @Autowired
    private SMSUtils smsUtils;
    @RabbitListener(queues = "phoneCode")
    public void getCode(String phone){
        try {
            //随机生成4位数字验证码
            String code = (int)((Math.random()*9+1)*1000)+"";
            //发送验证码
            smsUtils.sendMessage(phone, "阿里云短信测试", "SMS_154950909", code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 @RabbitListener(queues = "phoneCode")监听交换机,发送给队列的信息

注意队列和交换机关系要绑定好。(不知道怎么绑定的,可以先学一下rabbitmq)

3 发送短信的工具类

@Component
public class SMSUtils {
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 阿里云登录id
     */
    private final static String ACCESS_KEY_ID = "。。。。。。。。";
 
    /**
     * 阿里云登录密码
     */
    private final static String ACCESS_KEY_SECRET = "。。。。。。。。。";
 
    /**
     * 初始化登录阿里云的Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
        .setAccessKeyId(accessKeyId)
        .setAccessKeySecret(accessKeySecret);
        // 可指定登录的服务器地址,可参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
 
    /**
     * 发送短信方法
     * @param phoneNumbers 手机号
     * @param signName 签名
     * @param templateCode  模板编号
     * @param code 模板参数
     * @throws Exception
     */
    public  void sendMessage(String phoneNumbers, String signName, String templateCode, String code) throws Exception {
        System.out.println(11);
        //hashmap转化位json
        HashMap<String, String> map = new HashMap<>();
        map.put("code", code);
        String jsonCode = JSONUtil.toJsonStr(map);


        com.aliyun.dysmsapi20170525.Client client = SMSUtils.createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
        .setPhoneNumbers(phoneNumbers)
        .setSignName(signName)
        .setTemplateCode(templateCode)
        .setTemplateParam(jsonCode);
        SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());

        if(sendSmsResponse.getBody().code.equals("OK")){
            System.out.println("短信发送成功");
           //短信验证码存储在redis,五分钟过期
            redisUtil.setCacheObject("phone::code"+phoneNumbers,code,5,TimeUnit.MINUTES);


        }else {
            System.out.println(sendSmsResponse.getBody().message);
            System.out.println("短信发送失败");
        }

    }
 

 
}

ACCESS_KEY_ID和ACCESS_KEY_SECRET需要更换为自己的哦,获取方式如下

点击创建

 

4 还有一些工具类如下

package org.example.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * spring redis 工具类
 *
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisUtil {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 删除Hash中的数据
     *
     * @param key
     * @param hKey
     */
    public void delCacheMapValue(final String key, final String hKey) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }
}

 5 application.yml

server:
  port: 9005
spring:
  application:
    name: my-consumer
  rabbitmq:
    host: 47.122.62.29 # 你的虚拟机IP
    port: 5672 # 端口
    virtual-host: / # 虚拟主机
    username: lsw # 用户名
    password: 123456 # 密码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值