How to store Java objects in Redis

Redis is one of the most poplar caching solution currently used by various companies. It can act as a cache as well as database and is a simple key-value storage system. As we know it can only store strings as values, how to store Java objects apart from the collections like list,map etc it already supports?

Well simple answer is to serialize the objects into byte arrays before storing them in the redis. The object to be stored needs to be serializable

 private static String toString( Serializable o ) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream( baos );
        oos.writeObject( o );
        oos.close();
        return Base64.getEncoder().encodeToString(baos.toByteArray()); 
    }

Similarly whenever we fetch this value we should deserialize it into the object

    /** Read the object from Base64 string. */
    private static Object fromString( String s ) throws IOException ,
                                                        ClassNotFoundException {
         byte [] data = Base64.getDecoder().decode( s );
         ObjectInputStream ois = new ObjectInputStream( 
                                         new ByteArrayInputStream(  data ) );
         Object o  = ois.readObject();
         ois.close();
         return o;
    }

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *