基于Redis的Hash实现用户注册

本文介绍了如何使用Redis的Hash数据结构高效存储用户注册信息,包括用户实体定义、常量类设置、IP获取工具和注册控制器的实现。重点讲解了如何将用户对象转化为Hash并设置过期时间以优化内存利用。

基于Redis的Hash实现用户注册

流程:

  1. 注册用户填写用户信息,先写入到db中
  2. 在存储数据到redis的hash结构中 key=”reg:user:id”

1、定义user实体

package com.example.entity;

import lombok.Data;

/**
 * @Auther: 长颈鹿
 * @Date: 2021/08/17/17:19
 * @Description:
 */
@Data
public class User implements java.io.Serializable {

    private Integer id;
    // 昵称
    private String nickname;
    // 密码
    private String password;
    // 性别 0女 1男 2保密
    private Integer male;
    // 删除状态 0 未删除 1删除
    private Integer isDelete;

}

2、常量类RedsConstants

package com.example.constants;

/**
 * @Auther: 长颈鹿
 * @Date: 2021/08/17/18:22
 * @Description:
 */
public class RedsConstants {

    // 用户注册
    public static final String REG_HASH_USER = "reg:user:hash:";
    // 发送微博
    public static final String INSERT_HASH_CONTENT = "insert:hash:content";
}

3、工具类IPUtils & ObjectUtils

package com.example.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: 长颈鹿
 * @Date: 2021/08/17/18:16
 * @Description:
 */
public class IPUtils {

    private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

    /**
     * 获取IP地址
     * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
            logger.error("IPUtils ERROR ", e);
        }
        // 使用代理,则获取第一个IP地址
        if (StringUtils.isEmpty(ip) && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

}
package com.example.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: 长颈鹿
 * @Date: 2021/08/17/18:13
 * @Description:
 */
public class ObjectUtils {

    private static final String JAVAP = "java.";
    private static final String JAVADATESTR = "java.util.Date";

    /**
     * 获取利用反射获取类里面的值和名称
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    /**
     * 利用递归调用将Object中的值全部进行获取
     *
     * @param timeFormatStr 格式化时间字符串默认<strong>2017-03-10 10:21</strong>
     * @param obj           对象
     * @param excludeFields 排除的属性
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, String> objectToMap(String timeFormatStr, Object obj, String... excludeFields) throws IllegalAccessException {
        Map<String, String> map = new HashMap<>();

        if (excludeFields.length!=0){
            List<String> list = Arrays.asList(excludeFields);
            objectTransfer(timeFormatStr, obj, map, list);
        }else{
            objectTransfer(timeFormatStr, obj, map,null);
        }
        return map;
    }

    /**
     * 递归调用函数
     *
     * @param obj           对象
     * @param map           map
     * @param excludeFields 对应参数
     * @return
     * @throws IllegalAccessException
     */
    private static Map<String, String> objectTransfer(String timeFormatStr, Object obj, Map<String, String> map, List<String> excludeFields) throws IllegalAccessException {
        boolean isExclude=false;
        //默认字符串
        String formatStr = "YYYY-MM-dd HH:mm:ss";
        //设置格式化字符串
        if (timeFormatStr != null && !timeFormatStr.isEmpty()) {
            formatStr = timeFormatStr;
        }
        if (excludeFields!=null){
            isExclude=true;
        }
        Class<?> clazz = obj.getClass();
        //获取值
        for (Field field : clazz.getDeclaredFields()) {
            String fieldName = clazz.getSimpleName() + "." + field.getName();
            //判断是不是需要跳过某个属性
            if (isExclude&&excludeFields.contains(fieldName)){
                continue;
            }
            //设置属性可以被访问
            field.setAccessible(true);
            Object value = field.get(obj);
            Class<?> valueClass = value.getClass();
            if (valueClass.isPrimitive()) {
                map.put(fieldName, value.toString());

            } else if (valueClass.getName().contains(JAVAP)) {//判断是不是基本类型
                if (valueClass.getName().equals(JAVADATESTR)) {
                    //格式化Date类型
                    SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
                    Date date = (Date) value;
                    String dataStr = sdf.format(date);
                    map.put(fieldName, dataStr);
                } else {
                    map.put(fieldName, value.toString());
                }
            } else {
                objectTransfer(timeFormatStr, value, map,excludeFields);
            }
        }
        return map;
    }

}

4、定义注册的RegController

package com.example.controller;

import com.example.constants.RedsConstants;
import com.example.entity.User;
import com.example.utils.ObjectUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 长颈鹿
 * @Date: 2021/08/17/17:20
 * @Description:
 */
@RestController
public class RegController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("regUser")
    @ApiOperation("用户注册")
    public String regUser(User user) throws IllegalAccessException {
        // 把用户注册到DB中
//        userService.saveOrUpdate(user);
        // 查询最新的用户信息放入到redis的hash重
//        User user1 = userService.getById(user.getId());
        // 将对象转换map
        Map<String, Object> map = ObjectUtils.objectToMap(user);
        // 准备用存入的key,将用户信息存入到redis的hash中
        String key = RedsConstants.REG_HASH_USER + user.getId();
        redisTemplate.opsForHash().putAll(key, map);
        // 设置key的失效时间一个月
        redisTemplate.expire(key, 30, TimeUnit.DAYS);

        return "success";
    }

}

核心代码

Map<String, Object> map = ObjectUtils.objectToMap(user);
// 准备用存入的key,将用户信息存入到redis的hash中
String key = RedsConstants.REG_HASH_USER + user.getId();
redisTemplate.opsForHash().putAll(key, map);

分析代码

 // 设置key的失效时间一个月
redisTemplate.expire(key, 30, TimeUnit.DAYS);

设置过期时间作用:防止用户注册以后不使用任何服务。如果不设置过期时间,可能会造成内存的浪费。

5、查看存储信息

127.0.0.1:6379> hgetall reg:user:hash:1
 1) "password"
 2) "\"123456\""
 3) "isDelete"
 4) "1"
 5) "nickname"
 6) "\"\xe5\x88\x98\xe5\xa4\xa7\""
 7) "id"
 8) "1"
 9) "male"
10) "1"
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南宫拾壹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值