短信验证

24次阅读

共计 1955 个字符,预计需要花费 5 分钟才能阅读完成。

在本周的项目中用到了一个手机短信验证的功能,虽然代码都是已经写好了的,自己只是拿来就用,但事后还是得学习一下思路的。

短信验证整体思路

主要流程如下

基础功能还是比较简单的毕竟发短信用到是现成的接口,本项目用到的短信验证接口的网站是这个

  /**
     * 批量发送短信
     *
     * @param phoneNumbers
     * @param message      短信内容
     * @return 成功 200,不成功 400(短信验证错误或未传入发送手机号)
     * @throws IOException 
     */
    @Override
        public Integer sentMessage(Set<String> phoneNumbers, String message) throws IOException {HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(sOpenUrl);
            // 在头文件中设置转码
            post.addRequestHeader("Content-Type", ContentType);
            // 注册的用户名
            NameValuePair[] data = {new NameValuePair("action", "sendOnce"),
                    // 注册成功后, 登录网站使用的密钥
                    new NameValuePair("ac", account),
                    // 手机号码
                    new NameValuePair("authkey", authkey),
                    new NameValuePair("cgid", cgid.toString()),
                    new NameValuePair("c", message),
                    new NameValuePair("m", String.join(",", phoneNumbers))}; // 设置短信内容

            post.setRequestBody(data);

            client.executeMethod(post);
            post.releaseConnection();
            return post.getStatusCode();}

小难点

主要的难点我认为主要就是:怎么保存已经发送的验证码并判断是否失效。
在本项目中是直接通过一个服务中的 hashMap 把验证码与手机号的信息直接存到内存中,毕竟本项目同时注册人数不可能太多,而几个字符串内存还是承受的住的。

        HashMap<String, HashMap<String, Object>> hashMap = new HashMap<>();  // 缓存值
        String EXPIRE_DATE_KEY = "expireDate";  // 数据失效时间关键字(指在某个时间失效)String VALUE_KEY = "value";  // 存数据的 KEY    
    
        // 存放缓存的方法
        static void put(String key, Object object, Integer expireTime) {HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put(MemoryCacheService.VALUE_KEY, object);
            hashMap.put(MemoryCacheService.EXPIRE_DATE_KEY, System.currentTimeMillis() + expireTime * 1000);
            MemoryCacheService.hashMap.put(key, hashMap);
        }

通过手机号查询验证码

    /**
     * 获取缓存
     *
     * @param key
     * @return
     */
    static Object get(String key) {if (MemoryCacheService.shouldClearExpiredData()) {logger.info("定期清除过期缓存");
            MemoryCacheService.clearExpiredData();}

        HashMap<String, Object> cachedObject = MemoryCacheService.getCachedObjectByKey(key);
        if (cachedObject == null) {return null;    // 未获取到缓存数据,返回 null}

        if (MemoryCacheService.isExpired(cachedObject)) {logger.info("缓存过期,清除缓存. 返回 null");
            MemoryCacheService.remove(key);
            return null;
        }

        return cachedObjec

总结

本以为这个功能的博客能写不少,毕竟还是让我感觉很新鲜的,但真的开始才发现没啥重点可写,限制 ip 请求次数的功能
还写掉了,要是详细写怎么实现的感觉又没必要,毕竟逻辑实际上还是很简单的看看流程图就能理解了,就这样吧。

正文完
 0