LWM

redisDao.java

package com.example.demo.dao;

/**
 * @Date 2023/7/1 - 9:11
 */
public interface redisDao {
    //    存储验证码
    boolean save(String telephone, String code);

    //    获取验证码
    String getCode(String telephone);

    //    存储token
    void setToken(String key, String value);

    //    获取token
    String getToken(String key);
}

redisDaoImpl.java

package com.example.demo.dao;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Date 2023/7/1 - 9:14
 */
@Repository
public class redisDaoImpl implements redisDao {

    //    将操作redis数据库的对象进行注入
    @Resource
    private RedisTemplate redisTemplate;

    //    存储验证码
    @Override
    public boolean save(String telephone, String code) {
        ValueOperations op = redisTemplate.opsForValue();
//        设置验证码失效时长2分钟
        try {
            op.set(telephone, code, 120, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }

    //    获取验证码
    @Override
    public String getCode(String telephone) {
        ValueOperations op = redisTemplate.opsForValue();
        String code = (String) op.get("telephone");
        return code;
    }

    //    存储token
    @Override
    public void setToken(String key, String value) {
        ValueOperations op = redisTemplate.opsForValue();
//        设置过期时间1小时
        op.set(key, value, 1, TimeUnit.HOURS);
    }

    //    获取token
    @Override
    public String getToken(String key) {
        ValueOperations op = redisTemplate.opsForValue();
        String value = (String) op.get(key);
        return value;
    }
}

使用说明:用的时候将redisDao装配进来

 

posted on 2023-07-01 09:55  Lwmm  阅读(15)  评论(0编辑  收藏  举报