手机验证码如何储存在redis数据库中(spring 集成redis)

业务需求:通过手机号获取验证码,后台将验证码存放在redis数据库,供登录验证;

配置pom,加载依赖jar包:spring-data-redis、redis.clients两个依赖jar包

<dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.8.0</version>
            </dependency>
            <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.5.0.RELEASE</version>
    </dependency>

spring-redis.xml配置文件

<!-- 配置redis连接池  -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="100"/><!-- 最大闲置 -->
        <property name="minIdle" value="10"/><!-- 最小闲置 -->
        <property name="testOnBorrow" value="true"/><!-- 可以获取 -->
<!--        <property name="testOnReturn" value="true"/>-->
    </bean>
    <!-- redis 配置,也可以把配置挪到properties配置文件中,再读取 -->
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig" />
        <!-- 端口,默认6379 -->
        <constructor-arg index="2" value="6379"  name="port" type="int"/>
        <constructor-arg index="3" value="5000"  name="timeout" type="int"/>
        <constructor-arg index="1" value="127.0.0.1" name="host" type="java.lang.String"/>
        <!-- 如果你需要配置密码,请打开这里。
            <constructor-arg index="4" value="你的密码" name="password" type="java.lang.String"/>
        -->
    </bean>

创建Jedis管理者:JedisManager

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.waims.webset.common.utils.LoggerUtils;
import com.waims.webset.common.utils.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

/**
 * 获取Jedis以及一些jedis操作
 * <p>
 * 
 * Redis Manager Utils
 * 
 * <p>
 * 
 * 区分 责任人 日期    说明<br/>
 * 创建 郭佳庆 2018年1月3日  <br/>
 *
 * @author guojiaqing
 * @version 1.0,2018年1月3日 <br/>
 * 
 */
@Component
public class JedisManager {
    @Autowired
    private JedisPool jedisPool;

    public Jedis getJedis() {
        Jedis jedis = null;
        try {
            jedis = getJedisPool().getResource();
        } catch (JedisConnectionException e) {
            String message = StringUtils.trim(e.getMessage());
            if("Could not get a resource from the pool".equalsIgnoreCase(message)){
                System.out.println("++++++++++请检查你的redis服务++++++++");
                System.exit(0);//停止项目
            }
            throw new JedisConnectionException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jedis;
    }

    public void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
        /**
         * @deprecated starting from Jedis 3.0 this method will not be exposed.
         * Resource cleanup should be done using @see {@link redis.clients.jedis.Jedis#close()}
        if (isBroken){
            getJedisPool().returnBrokenResource(jedis);
        }else{
            getJedisPool().returnResource(jedis);
        }
        */
        jedis.close();
    }
    /**
     * 获取redis缓存数据库的value
     * @param dbIndex 选择redis数据库
     * @param key
     * @return
     * @throws Exception
     */
    public String getValueByKey(int dbIndex, String key) throws Exception {
        Jedis jedis = null;
        String result = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            result = jedis.get(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
        return result;
    }
    /**
     * 删除redis数据库数据
     * @param dbIndex
     * @param key
     * @throws Exception
     */

    public void deleteByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            Long result = jedis.del(key);
            LoggerUtils.fmtDebug(getClass(), "删除Session结果:%s" , result);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }
    /**
     * 保存redis数据,设置过期时间
     * @param dbIndex
     * @param key
     * @param value
     * @param expireTime  key的过期时间
     * @throws Exception
     */
    public void saveValueByKey(int dbIndex, String key, String value, int expireTime)
            throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.set(key, value);
            if (expireTime > 0)
                jedis.expire(key, expireTime);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }
    /**
     * 获取redis连接池
     * @return
     */
    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

}

保存验证码

public ResultRecord reslut(String phonenum) {
        ResultRecord rr=null;
        Jedis jedis=null;
        try{
            jedis=jm.getJedis();
            //生成verification code
            String code=VerifyCodeUtil.generateTextCode(0, 6, null);
            jm.saveValueByKey(1, phonenum, code, 120);
            System.out.println("生成的验证码为:"+code);
            System.out.println("成功保存到redis数据库");
            System.out.println("key:"+phonenum+";value:"+code);
            System.out.println("redis数据库中取出value:"+jm.getValueByKey(1, phonenum));
            String text="(中国心理学会)您的验证码为"+code+",如非本人操作请忽略;";
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String nowtime=sdf.format(date);
            RecordInfo record=new RecordInfo();
            record.setPhonenum(phonenum);
            record.setVerifitationcode(code);
            record.setGettime(nowtime);
            record.setLoginstate("0");
            int result=rif.insertSelective(record);
            String url="";
            List<NameValuePair> list=new ArrayList<NameValuePair>();
            NameValuePair name=new BasicNameValuePair("CorpID","");
            NameValuePair pwd=new BasicNameValuePair("pwd","");
            NameValuePair phone=new BasicNameValuePair("Mobile",phonenum);
            NameValuePair content=new BasicNameValuePair("Content",text);
            NameValuePair cell=new BasicNameValuePair("Cell","");
            NameValuePair sendtime=new BasicNameValuePair("SendTime","");
            list.add(name);
            list.add(pwd);
            list.add(phone);
            list.add(content);
            list.add(cell);
            list.add(sendtime);
            //String msg=HttpClientUtil.httpPost(url, list);
            System.out.println("开始发送");
            rr=new ResultRecord();
            rr.setMsg("msg");
            rr.setResult(result);
            return rr;
        }catch(Exception e){
            e.printStackTrace();
        }
        rr=new ResultRecord();
        return null;
    }

}

当用户提交验证码后,去redis数据库进行匹配就可以了!
以上就是和大家的分享,还希望喜欢!有不懂得可以加qq:1017228248

猜你喜欢

转载自blog.csdn.net/qq_36938933/article/details/78984312
今日推荐