一分钟之内只能发送一次短信,
若用户刷新页面,然后输入原来的手机号,则继续计时
方案:服务器端要记录时间戳
方法名:sMSWaitingTime
功能:返回倒计时剩余时间,单位秒
- /***
- * 倒计时还剩余多长时间
- * @param mobile : 手机号
- * @return : second
- */
- public int sMSWaitingTime(String mobile) {
- HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
- HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
- RedisHelper rdsHelper = RedisHelper.getInstance();
- String cid = getCid(request, response);
- String lastSendSMSTime = rdsHelper.getCache(cid+mobile);//getKeyCache(request, response, mobile) ;
- if(StringUtil.isNullOrEmpty(lastSendSMSTime)) {
- saveExpxKeyCache(request, response, mobile, String.valueOf(DateTimeUtil.getCurrentTimeSecond()),60);
- return 0;
- } else {
- long lastSendSMSTimeSecond=Long.parseLong(lastSendSMSTime);
- long currentTimeSecond=DateTimeUtil.getCurrentTimeSecond();
- int delter=(int) (currentTimeSecond-lastSendSMSTimeSecond);
- System.out.println("delter:"+delter);
- if(delter>=60){
- return 0;
- }else{
- return 60-delter;
- }
- }
- }
jedis 可以设置key的超时时间:
- public /*synchronized*/ void saveExpxKeyCache(HttpServletRequest request, HttpServletResponse response, String k, String v,long time) {
- String cid = getCid(request, response);
- // logger.debug("cid is " + cid);
- // logger.debug("set " + k + " to value : " + v);
- RedisHelper helper = RedisHelper.getInstance();
- helper.saveExpxKeyCache(cid+k, v,time);
- // jedis.hset(httpSession.getId(), k, v);
- // jedis.expire(httpSession.getId(), 3600);
- }
- /***
- * Only set the key if it does not already exist
- *
- * @param k
- * @param v
- * @param time : second
- */
- public void saveExpxKeyCache(String k, String v, long time) {
- saveExpxKeyCache(k, v, "NX", time);
- }
- /***
- * @param k
- * @param v
- * @param nxxx : NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the key
- * if it already exist.
- * @param time : second
- */
- public void saveExpxKeyCache(String k, String v, String nxxx, long time) {
- Jedis jedis = Const.pool.getResource();
- try {
- jedis.set(k, v, nxxx, "EX"/*seconds*/, time);
- } catch (Exception e) {
- e.printStackTrace();
- logger.error("saveKeyCache", e);
- Const.pool.returnBrokenResource(jedis);
- jedis = null;
- } finally {
- if (jedis != null) {
- Const.pool.returnResource(jedis);
- }
- }
- }
参考:
http://hw1287789687.iteye.com/blog/2225130