如何使用Java redis實(shí)現(xiàn)發(fā)送手機(jī)驗(yàn)證碼功能
要求:
1、輸入手機(jī)號(hào),點(diǎn)擊發(fā)送后隨機(jī)生成6位數(shù)字碼,2分鐘有效
2、輸入驗(yàn)證碼,點(diǎn)擊驗(yàn)證,返回成功或失敗
3、每個(gè)手機(jī)號(hào)每天只能輸入3次
代碼如下
import redis.clients.jedis.Jedis;import java.util.Random;public class ValidationTest { public static void main(String[] args) { //getValidation('15005076571'); //checkValidation('769897','15005076571'); } static void getValidation(String tel) { //主機(jī)、端口 Jedis jedis = new Jedis('myhost', 6379); //密碼 jedis.auth('mypassword'); try { //獲取電話號(hào)碼 String phoneNo = tel; //本人用1庫(kù)進(jìn)行測(cè)試 jedis.select(1); String countKey = phoneNo + ':count'; String codeKey = phoneNo + ':code'; //獲取指定的電話號(hào)碼發(fā)送的驗(yàn)證碼次數(shù) String cnt = jedis.get(countKey); //對(duì)次數(shù)進(jìn)行判斷 if (cnt == null) {//沒有發(fā)送過驗(yàn)證碼jedis.setex(countKey, 60 * 60 * 24, '1');//發(fā)送驗(yàn)證碼,假設(shè)生成的驗(yàn)證碼StringBuffer code = new StringBuffer();for (int i = 0; i < 6; i++) { code.append(new Random().nextInt(10));}System.out.println('code:' + code);//緩存中添加驗(yàn)證碼jedis.setex(codeKey, 60 * 2, code.toString()); } else {if (Integer.parseInt(cnt) < 3) { //發(fā)送驗(yàn)證碼,假設(shè)生成的驗(yàn)證碼 StringBuffer code = new StringBuffer(); for (int i = 0; i < 6; i++) { code.append(new Random().nextInt(10)); } System.out.println('code:' + code); //緩存中添加驗(yàn)證碼 jedis.setex(codeKey, 60 * 2, code.toString()); //遞增手機(jī)發(fā)送數(shù)量 jedis.incr(countKey);} else { //返回超出3次,禁止發(fā)送 System.out.println('超出3次,禁止發(fā)送');} } } catch (Exception e) { //這邊其實(shí)是需要回滾下redis e.printStackTrace(); } finally { //關(guān)閉redis if (jedis != null) {jedis.close(); } } } static void checkValidation(String code, String tel) { Jedis jedis = null; try { jedis = new Jedis('myhost', 6379); //密碼 jedis.auth('mypassword'); jedis.select(1); String codeKey = tel + ':code'; String validation = jedis.get(codeKey); if (validation == null) {System.out.println('驗(yàn)證碼未發(fā)送或者失效'); } else {if (validation.equals(code)) { System.out.println('驗(yàn)證成功');} else { System.out.println('驗(yàn)證失敗');} } } catch (Exception e) { e.printStackTrace(); } finally { if (jedis != null) {jedis.close(); } } }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法2. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析3. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問題4. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法5. Nginx+php配置文件及原理解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向8. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)9. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼10. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解
