Redis 存储Java 对象 (序列化和反序列化)

Redis的string 类型是二进制安全的,可以储存 序列化的对象。因此可以通过序列化储存java对象,再通过反序列化得到对象。

新建一个maven项目,添加相关的Jar包依赖。

<dependencies>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>
</dependencies>

项目创建好后,首先,创建一个工具类,用于序列化和反序列化

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
    public static byte[] serialize(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) {
            System.out.println(e);
        }
        return null;
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            //反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }
}

其次,创建一个测试类,需注意该测试类必须实现serializable接口,否则会报错。

import java.io.Serializable;

public class students implements Serializable {
    private String name="";
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

最后,测试运行

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class redis {
    public static void main(String[] args) {

        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大空闲数
        poolConfig.setMaxIdle(50);
        // 最大连接数
        poolConfig.setMaxTotal(100);
        // 最大等待毫秒数
        poolConfig.setMaxWaitMillis(20000);
        // 使用配置创建连接池
        JedisPool pool = new JedisPool(poolConfig, "localhost");
        // 从连接池中获取单个连接
        Jedis jedis = pool.getResource();
        // 如果需要密码
        //jedis.auth("password");
        //连接本地的 Redis 服务
        System.out.println("连接成功");

        students stu = new students();
        stu.setAge(21);
        stu.setName("Henry");

        //序列化java对象,并储存到Redis
        byte[] serialize = SerializeUtil.serialize(stu);
        jedis.set("student".getBytes(),  serialize);

        //获取对象的序列化值,并反序列化为java对象
        byte[] result = jedis.get("student".getBytes());
        students obj =(students) SerializeUtil.unserialize(result);
        System.out.println("student: " + obj.getName()+obj.getAge());


    }
}

 

很高兴帮助你解答问题。以下是Java redis序列化反序列化的示例代码: Redis序列化对象: ``` import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import org.springframework.util.Assert; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class RedisObjectSerializer implements RedisSerializer<Object> { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; public RedisObjectSerializer() { super(); } public byte[] serialize(Object obj) throws SerializationException { if (obj == null) { return EMPTY_BYTE_ARRAY; } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream); objectOutputStream.writeObject(obj); objectOutputStream.flush(); return byteStream.toByteArray(); } catch (Throwable ex) { throw new SerializationException("Failed to serialize", ex); } } public Object deserialize(byte[] bytes) throws SerializationException { if (isEmpty(bytes)) { return null; } try { ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); return objectInputStream.readObject(); } catch (Throwable ex) { throw new SerializationException("Failed to deserialize", ex); } } private boolean isEmpty(byte[] data) { return (data == null || data.length == 0); } } ``` Redis反序列化对象: ``` import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import org.springframework.util.Assert; import java.nio.charset.Charset; public class RedisStringSerializer implements RedisSerializer<String> { private final Charset charset; public RedisStringSerializer() { this(Charset.forName("UTF8")); } public RedisStringSerializer(Charset charset) { Assert.notNull(charset, "Charset must not be null!"); this.charset = charset; } public String deserialize(byte[] bytes) { return (bytes == null ? null : new String(bytes, charset)); } public byte[] serialize(String string) throws SerializationException { return (string == null ? null : string.getBytes(charset)); } } ``` 请注意,这里使用了Spring Data Redis库,并实现了RedisSerializer接口。您可以根据需要使用其他Redis客户端库和其他序列化器。希望这可以帮助到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值