黑马点评Redis笔记

Redis基础篇:https://cyborg2077.github.io/2022/10/21/RedisBasic/
Redis实战篇:https://cyborg2077.github.io/2022/10/22/RedisPractice/

一、手机号+验证码注册登录

RandomUtil

生成定长随机数列
String code = RandomUtil.randomNumbers(6);

返回类型约定

public class Result {
    private Boolean success;
    private String errorMsg;
    private Object data;
    private Long total;

    public static Result ok(){
        return new Result(true, null, null, null);
    }
    public static Result ok(Object data){
        return new Result(true, null, data, null);
    }
    public static Result ok(List<?> data, Long total){
        return new Result(true, null, data, total);
    }
    public static Result fail(String errorMsg){
        return new Result(false, errorMsg, null, null);
    }
}

正则类

校验手机号

RegexUtils.isPhoneInvalid(phone);
public class RegexUtils {
    /**
     * 是否是无效手机格式
     * @param phone 要校验的手机号
     * @return true:符合,false:不符合
     */
    public static boolean isPhoneInvalid(String phone){
        return mismatch(phone, RegexPatterns.PHONE_REGEX);
    }
    /**
     * 是否是无效邮箱格式
     * @param email 要校验的邮箱
     * @return true:符合,false:不符合
     */
    public static boolean isEmailInvalid(String email){
        return mismatch(email, RegexPatterns.EMAIL_REGEX);
    }

    /**
     * 是否是无效验证码格式
     * @param code 要校验的验证码
     * @return true:符合,false:不符合
     */
    public static boolean isCodeInvalid(String code){
        return mismatch(code, RegexPatterns.VERIFY_CODE_REGEX);
    }

    // 校验是否不符合正则格式
    private static boolean mismatch(String str, String regex){
        if (StrUtil.isBlank(str)) {
            return true;
        }
        return !str.matches(regex);
    }
}

ThreadLocal工具类

public class UserHolder {
    private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();

    public static void saveUser(UserDTO user){
        tl.set(user);
    }

    public static UserDTO getUser(){
        return tl.get();
    }

    public static void removeUser(){
        tl.remove();
    }
}

BeanUtil使用

属性拷贝BeanUtil.copyProperties
UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
对象转哈希BeanUtil.beanToMap
Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
        CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

随机生成token

String token = UUID.randomUUID().toString(true);

Redis存登录信息

String tokenKey = LOGIN_USER_KEY + token;
stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
// 7.4.设置token有效期
stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

二、缓存

字符串工具StrUtil

StrUtil.isNotBlank(shopJson)

Json工具JSONUtil

Json字符串转对象

String shopJson = stringRedisTemplate.opsForValue().get(key);
Shop shop = JSONUtil.toBean(shopJson, Shop.class);

对象转Json字符串

JSONUtil.toJsonStr(shop)

缓存穿透

缓存雪崩

缓存击穿

黑马点评Redis笔记-LMLPHP
黑马点评Redis笔记-LMLPHP

11-26 17:43