必须引用序列化Serializable接口

创建类:Role

package com.wbg.springRedis.entity; 
 
import java.io.Serializable; 
 
public class Role implements Serializable { 
    private int id; 
    private String roleName; 
    private String note; 
    @Override 
    public String toString() { 
        return "Role{" + 
                "id=" + id + 
                ", roleName='" + roleName + '\'' + 
                ", note='" + note + '\'' + 
                '}'; 
    } 
 
    public Role() { 
    } 
 
    public Role(String roleName, String note) { 
        this.roleName = roleName; 
        this.note = note; 
    } 
 
    public Role(int id, String roleName, String note) { 
        this.id = id; 
        this.roleName = roleName; 
        this.note = note; 
    } 
 
    public int getId() { 
        return id; 
    } 
 
    public void setId(int id) { 
        this.id = id; 
    } 
 
    public String getRoleName() { 
        return roleName; 
    } 
 
    public void setRoleName(String roleName) { 
        this.roleName = roleName; 
    } 
 
    public String getNote() { 
        return note; 
    } 
 
    public void setNote(String note) { 
        this.note = note; 
    } 
}

创建RoleRedisStream类(该类就是调用公共类)

package com.wbg.springRedis.redis; 
import redis.clients.jedis.Jedis; 
 
import java.io.*; 
import java.util.List; 
 
public class RoleRedisStream  { 
 
    public  void byteArrayOutputStream(Jedis jedis, List<?> list, String key) throws IOException { 
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        ObjectOutputStream oos = new ObjectOutputStream(bos); 
        oos.writeObject(list); 
        jedis.set(key.getBytes(),bos.toByteArray()); 
        oos.close(); 
    } 
 
    public List<?> byteArrayInputStream(Jedis jedis,String key) throws IOException, ClassNotFoundException { 
        ByteArrayInputStream bis = new ByteArrayInputStream(jedis.get(key.getBytes())); 
        ObjectInputStream ois = new ObjectInputStream(bis); 
        List<?> list1 = (List<?>) ois.readObject(); 
        ois.close(); 
        return list1; 
    } 
 
}

测试:

        RoleRedisStream roleRedisStream = new RoleRedisStream(); 
        List<Role> list = new ArrayList<>(); 
        for (int i = 0; i < 20; i++) { 
            Role role = new Role(i, "roleName" + i, "note" + i); 
            list.add(role); 
        } 
        //通过ObjectOutputStream序列化 
        roleRedisStream.byteArrayOutputStream(new Jedis(), list,"rolee2"); 
        //用过ObjectInputStream反序列化 
        System.out.println(roleRedisStream.byteArrayInputStream(new Jedis(), "rolee2"));

 

发布评论

分享到:

IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

装饰模式案列(OutputStream)讲解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。