Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jedis How to cache Java object

Tags:

java

redis

jedis

Using Redis Java client Jedis
How can I cache Java Object?

like image 291
DP Dev Avatar asked May 15 '15 06:05

DP Dev


People also ask

How do I cache a Java object in Redis?

You can't store objects directly into redis. So convert the object into String and then put it in Redis. In order to do that your object must be serialized. Convert the object to ByteArray and use some encoding algorithm (ex base64encoding) and convert it as String then store in Redis.

What is the difference between Redis and Jedis?

Jedis is a client library inside Redis that's designed for performance and ease of use. Jedis is a lightweight offering compared to other Redis Java clients; it offers fewer features but can still handle large amounts of memory.

How do I use Azure Redis cache in Java?

Create an Azure Cache for Redis. To create a cache, sign in to the Azure portal and select Create a resource. On the New page, select Databases and then select Azure Cache for Redis. On the New Redis Cache page, configure the settings for your new cache.

Does Jedis support Redis cluster?

The vast majority of the features from Redis are already available in Jedis, and its development moves forward at a good pace. It gives us the ability to integrate a powerful in-memory storage engine in our application with very little hassle.


2 Answers

You can't store objects directly into redis. So convert the object into String and then put it in Redis. In order to do that your object must be serialized. Convert the object to ByteArray and use some encoding algorithm (ex base64encoding) and convert it as String then store in Redis. While retrieving reverse the process, convert the String to byte array using decoding algorithm (ex: base64decoding) and the convert it to object.

like image 167
Karthikeyan Gopall Avatar answered Sep 21 '22 17:09

Karthikeyan Gopall


you should convert your object as a json string to store it, then read the json and transform it back to your object.

you can use Gson in order to do so.

//store
Gson gson = new Gson();
String json = gson.toJson(myObject);
jedis.set(key,json);

//restore
String json = jedis.get(key);
MyObject object=gson.fromJson(json, MyObject.class);
like image 30
jeorfevre Avatar answered Sep 18 '22 17:09

jeorfevre