Redis存储对象的三种方式

存储对象的三种方式分别为:

1.将对象序列化后保存到Redis
2.将对象用FastJSON转为JSON字符串后存储
3.将对象用Hash数据类型存储

这里RedisTemplate用自定义方式

/**
* 自定义RedisTemplate,修改其序列化方法
*/
@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
		// 创建RedisTemplate对象
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		// 设置连接工厂
		template.setConnectionFactory(connectionFactory);
		// 创建JSON序列化工具
		GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
		// 设置Key的序列化
		template.setKeySerializer(RedisSerializer.string());
		template.setHashKeySerializer(RedisSerializer.string());
		// 设置Value的序列化
		template.setValueSerializer(jsonRedisSerializer);
		template.setHashValueSerializer(jsonRedisSerializer);
		// 返回
		return template;
	}
}

序列化工具类SerializeUtil

public class SerializeUtil {
    /*
     * 序列化
     * */
    public static byte[] serizlize(Object object){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(baos != null){
                    baos.close();
                }
                if (oos != null) {
                    oos.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
    /*
     * 反序列化
     * */
    public static Object deserialize(byte[] bytes){
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null; 
        try{
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
}

User

public class User implements Serializable{
    private static final long serialVersionUID = -3210884885630038713L;
    private int id;
    private String name;
    public User(){
 
    }
    public User(int id,String name){
        this.id = id;
        this.name = name;
    }
    //setter和getter方法
}

方式1.将对象序列化后保存到Redis

@Component
public class VisitCounterScheduler {

    @Autowired
    private VisitCounterMapper visitCounterMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 59 * * * *")
    public void postDailyVisitCount2Redis() {
        redisTemplate.opsForValue().set("dailyVisitCount", SerializeUtil.serizlize(new User(2,"lumia")));
    }
}

方式2.将对象用FastJSON转为JSON字符串后存储

package com.aac.bpmmanager.scheduler;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
@Component
public class VisitCounterScheduler {

    @Autowired
    private VisitCounterMapper visitCounterMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 59 * * * *")
    public void postDailyVisitCount2Redis() {
        User user = new user(1, "zhangsanfeng");
        String s = JSON.toJSONString(user);
        //存放对象方式二:将对象用FastJSON转为JSON字符串后存储
        redisTemplate.opsForValue().set("user1", JSON.toJSONString(user));
    }
}

方式3.将对象用Hash数据类型存储

利用Hash存储对象,适用于字段的某些值经常变化,而部门值不变化,比如余额宝,余额经常变化可以用Hash存储,余额宝其它字段数据不经常变化。

package com.server;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pojo.Student;

@Service
public class StudentServer {

   @Autowired
   private RedisTemplate redisTemplate;//redisTemplate操作redis
   
   public void setmap(){
   	User stu=new User();
   	//标志map的键、标志value的key、value
   	//向键名为stu.getStuid的map对象存储key-value对
   	HashOperations<String, String, String> map=redisTemplate.opsForHash().put(stu.getId, "name", stu.getName);
   	
   	//设置100 seconds存活时间
   	redisTemplate.expire(stu.getStuid, 100, TimeUnit.SECONDS);
   }
}

参考文章
https://blog.csdn.net/qq_26545503/article/details/106123676
http://www.voidcn.com/article/p-rsqqqrgq-qw.html
https://blog.csdn.net/qq_44909430/article/details/104649464
https://blog.csdn.net/xzd315752647/article/details/86318870

  • 9
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 Java 中,将对象存储Redis 中有以下几种方式: 1. 将对象序列化为二进制数据,然后存储Redis 中。Java 中有多种序列化方式,如 JDK 自带的 Serializable 接口、Google 的 Protobuf、Apache 的 Avro 等。存储时可以使用 Redis 的二进制数据类型,如 `byte[]`、`String` 等。这种方式需要注意序列化和反序列化的性能问题,同时需要考虑序列化的兼容性问题。 2. 将对象转为 JSON 字符串,然后存储Redis 中。Java 中有多种 JSON 库,如 Google 的 Gson、阿里的 Fastjson 等。存储时可以使用 Redis 的字符串类型,如 `String`、`byte[]` 等。这种方式需要注意 JSON 库的性能问题,同时需要考虑 JSON 库的兼容性问题。 3. 将对象转为 Redis 的 Hash 结构,然后存储Redis 中。这种方式需要将对象的属性转为 Hash 的字段,可以使用 Java 反射机制进行转换。存储时可以使用 Redis 的 Hash 类型,如 `Map<String, String>`、`byte[]` 等。这种方式需要注意 Hash 字段和对象属性的映射关系,同时需要考虑 Hash 字段的数据类型问题。 4. 将对象转为 Redis 的 List 结构,然后存储Redis 中。这种方式需要将对象的属性转为 List 的元素,可以使用 Java 反射机制进行转换。存储时可以使用 Redis 的 List 类型,如 `List<String>`、`byte[]` 等。这种方式需要注意 List 元素和对象属性的映射关系,同时需要考虑 List 元素的数据类型问题。 需要注意的是,不同的存储方式适用于不同的场景,需要根据实际情况选择合适的方式。另外,存储Redis 中的数据需要考虑数据的安全性和可靠性问题,可以使用 Redis 提供的数据备份、持久化等功能进行保护。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值