springboot data redis 优雅的存取java实体类对象

前言

RedisTemplate是spring封装的操作redis的接口,使用起来很方便,但也有很多坑,比如存储javabean类。这里将使用fastjson实现序列化。非常滴人性!话不多说直接上demo

项目结构

|_config:配置文件目录
	|_FastJsonRedisSerializer.java
	|_RedisConfig.java
|_util
	|_RedisObjUtil.java
|_vo
	|_UserVo.java

配置类:(实现redis的序列化)

FastJsonRedisSerializer.java

package com.king.mooc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @program: mooc
 * @description:
 * @author: King
 * @create: 2021-10-06 21:08
 */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    private final Class<T> clazz;

    public FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return (T) JSON.parseObject(str, clazz);
    }

}

RedisConfig.java

package com.king.mooc.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.config.FastJsonConfig;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * @program: testSpring
 * @description:
 * @author: King
 * @create: 2021-05-08 20:44
 */
@Configuration
public class RedisConfig {


    RedisConfig(){
        //打开autotype功能,需要强转的类一次添加其后
        ParserConfig.getGlobalInstance()
                .addAccept("com.king.mooc.vo.UserVo");
    }

    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object,Object> template =new RedisTemplate<>();
        //template .setConnectionFactory(redisConnectionFactory);
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer=new FastJsonRedisSerializer<>(Object.class);
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(fastJsonRedisSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;

    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}


实体类 UserVO.java

package com.king.mooc.vo;

import com.king.mooc.bean.User;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * @program: mooc
 * @description:
 * @author: King
 * @create: 2021-10-06 15:08
 */
@Data
public class UserVo implements Serializable {
    private Long id;
    private String name;
    //头像
    private String headImg;
    private String email;
    private Long phone;
    //是否为会员
    private Boolean isVip = false;
    private String validateCode;


    public void setUser(User user) {
        System.out.println(user);
        this.id = user.getId();
        this.name = user.getName();
        this.email = user.getEmail();
        this.phone = user.getPhone();
        this.headImg = user.getHeadImg();
        this.isVip = user.getVipTime().isBefore(LocalDateTime.now());
    }

}

util

RedisObjUtil.java

package com.king.mooc.util;

import com.king.mooc.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Repository
public class RedisObjUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 存实体类
     * @param key key
     * @param o 实体类对象
     */
    public void setEntity(String key, Object o) {
        redisTemplate.opsForValue().set(key, o);
    }

    /**
     * 存实体类
     * @param key key
     * @param o 实体类对象
     * @param time 数据存储时间 单位分钟
     */
    public void setEntity(String key, long time, Object o) {
        redisTemplate.opsForValue().set(key, o, time, TimeUnit.MINUTES);
    }

    /**
     * 获取 UserVo 对象
     * @param key
     * @return UserVo
     */
    public UserVo getUserVo(String key) {
        return (UserVo) redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取实体类对象
     * @param key
     * @param entity
     * @param <T>
     * @return
     */
    public <T> T getEntity(String key, Class<T> entity) {
        return (T) redisTemplate.opsForValue().get(key);
    }
 }

测试类

package com.king.mooc.util;

import com.king.mooc.vo.UserVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class RedisObjUtilTest {
    @Autowired
    RedisObjUtil redisObjUtil;
    @Test
    public void setEntity(){
        UserVo userVo = new UserVo();
        userVo.setEmail("123456789@qq.com");
        userVo.setPhone(12345678941L);
        userVo.setId(1L);
        userVo.setName("test");
        userVo.setHeadImg("F:\\Downloads\\1.jpg");
        userVo.setIsVip(true);
        userVo.setValidateCode("K25sk");
        redisObjUtil.setEntity("userVo",userVo);
    }

    @Test
    public void getEntity(){
        UserVo userVo = redisObjUtil.getUserVo("userVo");
        System.out.println(userVo);

        UserVo userVo1 = redisObjUtil.getEntity("userVo",userVo.getClass());
        System.out.println(userVo1);
    }
}

运行结果

在这里插入图片描述

在这里插入图片描述

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值