Redis存放短信验证码 RedisTemplate =>opsForValue

@Autowired
private RedisTemplate redisTemplate;
  • redisTemplate.opsForValue()
  • redisTemplate.opsForHash()
  • redisTemplate.opsForList()
  • redisTemplate.opsForSet()
  • redisTemplate.opsForZSet()

Maven坐标:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>3.4.0</version>
        </dependency>
       

Controller层:
发送短信验证码存到redis中

@Autowired
    @Qualifier("stringRedisTemplate")
    RedisTemplate<String,String> rt;
    
    /*
     * 发送短信
     */
    @RequestMapping(value = "/sms")
    @ResponseBody
    public Map<String,Object> smsXxs( HttpServletRequest request) throws ClientException, ClientException {
        String phone = request.getParameter("phone");
        Map<String,Object> map = new HashMap<>();
// 验证码(指定长度的随机数)
        String code = CodeUtil.generateVerifyCode(6);
        String TemplateParam = "{\"code\":"+code+"}";
        //{'code':"+code+""}
        System.err.println("phome:=="+code);
            // 短信模板id
            String TemplateCode = "SMS_171113430";//如果使用不了(模板要更换属于自己的模板。)
            SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam,TemplateCode);
            map.put("verifyCode",code);
            map.put("phone",phone);
            request.getSession().setAttribute("CodePhone",map);
            if( response.getCode().equals("OK")) {
                map.put("isOk","OK");
            }
        //放入 redis中
        ValueOperations forValue = rt.opsForValue();
        forValue.set(phone, code);
        forValue.set("verifyPhone", phone);
        //设置过期时间
        rt.expire(phone, 90*1000, TimeUnit.MILLISECONDS);
        rt.expire("verifyPhone", 90*1000, TimeUnit.MILLISECONDS);
        System.err.println("Yess=========================");
            return map;

        }

从Redis中获取:
注册:

 /**
     *App 注册
     */
    @ResponseBody
    @RequestMapping("/app/add")
    @CrossOrigin
    public ResponseObject appuserAdd(DataUser bean, HttpServletRequest request){
        try {
            System.out.println("zhuce=====jinlail=====");
            String code1 = request.getParameter("code");
            String phone1 = request.getParameter("phone");
            System.out.println(code1);
            System.out.println(phone1);
            DataUser byId = userService.findByPhone(bean.getPhone());
            if(StringUitl.IsNotNull(byId)){
                return new ResponseObject(500,"手机号已注册!");
            }

            ValueOperations<String, String> forValue = rt.opsForValue();
            //redis中获取验证码
            String code0 = forValue.get(phone1);
            String phone0 = forValue.get("verifyPhone");
            System.out.println("redis=======");
            System.out.println(code0);
            System.out.println(phone0);
            if (code1.equals(code0) && phone1.equals(phone0)){
                System.out.println("yazhengtongguo");
                EncryptionMD5 md5 = new EncryptionMD5();
                String psw = md5.md5(bean.getPassword());
                bean.setPassword(psw);
                int i= userService.insertUser(bean);
                msg="注册成功";
                code=200;
                System.out.println("yes====");
            }else {
                return new ResponseObject(500,"验证码不正确!");
            }

        } catch (Exception e) {
            e.printStackTrace();
            msg="保存失败";
            code=500;
        }
        return new ResponseObject(code,msg);
    }

CodeUtil :

package com.langran.mingshuidata.controller.login;

import java.util.Random;

public class CodeUtil {
    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "1234567890";

    /**
     * 使用系统默认字符源生成验证码
     *
     * @param verifySize 验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }
    public static void main(String[] args) {
        System.out.println(generateVerifyCode(4));
    }
}

SmsTool :

package com.langran.mingshuidata.controller.login;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
  * @description: 手机号注册短信验证
  * @author  
  * @date 2021/5/11
  */
public class SmsTool {
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAILOpF1BQnVwJj";
    static final String accessKeySecret = "pvfsR48ZR7nTs1UePIifUCshaQpn7m";

    public static SendSmsResponse sendSms(String phone, String code, String TemplateCode) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
    //    request.setSignName("上面截图所要创建的签名");
        request.setSignName("黑马枪神GUN旅游网");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(TemplateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}",此处的值为
        request.setTemplateParam(code);
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");
        //hint 此处可能会抛出异常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }
}

**

opsForValue:

**

1、set(K key, V value) 新增一个字符串类型的值,key是键,value是值。

redisTemplate.opsForValue().set("stringValue","bbb");  

2、get(Object key) 获取key键对应的值。

String stringValue = redisTemplate.opsForValue().get("stringValue")+"";  
System.out.println("通过get(Object key)方法获取set(K key, V value)方法新增的字符串值:" + stringValue);  

3、append(K key, String value) 在原有的值基础上新增字符串到末尾。

redisTemplate.opsForValue().append("stringValue","aaa");  
String stringValueAppend = redisTemplate.opsForValue().get("stringValue")+"";  
System.out.println("通过append(K key, String value)方法修改后的字符串:"+stringValueAppend);  

4、get(K key, long start, long end) 截取key键对应值得字符串,从开始下标位置开始到结束下标的位置(包含结束下标)的字符串。

String cutString = redisTemplate.opsForValue().get("stringValue",0,3);  
System.out.println("通过get(K key, long start, long end)方法获取截取的字符串:"+cutString); 

5、getAndSet(K key, V value) 获取原来key键对应的值并重新赋新值。

String oldAndNewStringValue = redisTemplate.opsForValue().getAndSet("stringValue","ccc")+"";  
System.out.print("通过getAndSet(K key, V value)方法获取原来的" + oldAndNewStringValue + ",");  
String newStringValue = redisTemplate.opsForValue().get("stringValue")+"";  
System.out.println("修改过后的值:"+newStringValue);

6、setBit(K key, long offset, boolean value) key键对应的值value对应的ascii码,在offset的位置(从左向右数)变为value。

redisTemplate.opsForValue().setBit("stringValue",1,false);  
newStringValue = redisTemplate.opsForValue().get("stringValue")+"";  
System.out.println("通过setBit(K key,long offset,boolean value)方法修改过后的值:"+newStringValue);  

7、getBit(K key, long offset) 判断指定的位置ASCII码的bit位是否为1。

boolean bitBoolean = redisTemplate.opsForValue().getBit("stringValue",1);  
System.out.println("通过getBit(K key,long offset)方法判断指定bit位的值是:" + bitBoolean);  

8、size(K key) 获取指定字符串的长度。

Long stringValueLength = redisTemplate.opsForValue().size("stringValue");  
System.out.println("通过size(K key)方法获取字符串的长度:"+stringValueLength);  

9、increment(K key, double delta) 以增量的方式将double值存储在变量中。

double stringValueDouble = redisTemplate.opsForValue().increment("doubleValue",5);   
System.out.println("通过increment(K key, double delta)方法以增量方式存储double值:" + stringValueDouble);  

10、increment(K key, long delta) 以增量的方式将long值存储在变量中。

double stringValueLong = redisTemplate.opsForValue().increment("longValue",6);   
System.out.println("通过increment(K key, long delta)方法以增量方式存储long值:" + stringValueLong); 

11、setIfAbsent(K key, V value) 如果键不存在则新增,存在则不改变已经有的值。

boolean absentBoolean = redisTemplate.opsForValue().setIfAbsent("absentValue","fff");  
System.out.println("通过setIfAbsent(K key, V value)方法判断变量值absentValue是否存在:" + absentBoolean);  
if(absentBoolean){  
    String absentValue = redisTemplate.opsForValue().get("absentValue")+"";  
    System.out.print(",不存在,则新增后的值是:"+absentValue);  
    boolean existBoolean = redisTemplate.opsForValue().setIfAbsent("absentValue","eee");  
    System.out.print(",再次调用setIfAbsent(K key, V value)判断absentValue是否存在并重新赋值:" + existBoolean);  
    if(!existBoolean){  
        absentValue = redisTemplate.opsForValue().get("absentValue")+"";  
        System.out.print("如果存在,则重新赋值后的absentValue变量的值是:" + absentValue);  
    }  
}  

12、set(K key, V value, long timeout, TimeUnit unit) 设置变量值的过期时间。

redisTemplate.opsForValue().set("timeOutValue","timeOut",5,TimeUnit.SECONDS);  
String timeOutValue = redisTemplate.opsForValue().get("timeOutValue")+"";  
System.out.println("通过set(K key, V value, long timeout, TimeUnit unit)方法设置过期时间,过期之前获取的数据:"+timeOutValue);  
Thread.sleep(5*1000);  
timeOutValue = redisTemplate.opsForValue().get("timeOutValue")+"";  
System.out.print(",等待10s过后,获取的值:"+timeOutValue);  

13、set(K key, V value, long offset) 覆盖从指定位置开始的值。

redisTemplate.opsForValue().set("absentValue","dd",1);  
String overrideString = redisTemplate.opsForValue().get("absentValue")+"";  
System.out.println("通过set(K key, V value, long offset)方法覆盖部分的值:"+overrideString);  

14、multiSet(Map<? extends K,? extends V> map) 设置map集合到redis。

Map valueMap = new HashMap();  
valueMap.put("valueMap1","map1");  
valueMap.put("valueMap2","map2");  
valueMap.put("valueMap3","map3");  
redisTemplate.opsForValue().multiSet(valueMap); 

15、multiGet(Collection keys) 根据集合取出对应的value值。

//根据List集合取出对应的value值  
List paraList = new ArrayList();  
paraList.add("valueMap1");  
paraList.add("valueMap2");  
paraList.add("valueMap3");  
List<String> valueList = redisTemplate.opsForValue().multiGet(paraList);  
for (String value : valueList){  
    System.out.println("通过multiGet(Collection<K> keys)方法获取map值:" + value);  
}  
 

16、multiSetIfAbsent(Map<? extends K,? extends V> map) 如果对应的map集合名称不存在,则添加,如果存在则不做修改。

Map valueMap = new HashMap();  
valueMap.put("valueMap1","map1");  
valueMap.put("valueMap2","map2");  
valueMap.put("valueMap3","map3");  
redisTemplate.opsForValue().multiSetIfAbsent(valueMap); 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值