How to add hashmap into redis?

Member

by domenico , in category: Third Party Scripts , 5 months ago

How to add hashmap into redis?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 5 months ago

@domenico 

You cannot directly add a Java HashMap object into Redis, as Redis is a key-value store that only accepts string values. However, you can serialize the HashMap object into a JSON string and then store it in Redis using a specific key.


Here is an example of how you can add a HashMap into Redis using Jedis, a popular Java client for Redis:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import redis.clients.jedis.Jedis;
import com.google.gson.Gson;
import java.util.HashMap;

public class RedisExample {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");

        // Create a HashMap
        HashMap<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");

        // Serialize the HashMap into a JSON string
        Gson gson = new Gson();
        String json = gson.toJson(map);

        // Store the JSON string in Redis
        jedis.set("myHashMap", json);

        // Retrieve the HashMap from Redis
        String jsonFromRedis = jedis.get("myHashMap");
        HashMap<String, String> mapFromRedis = gson.fromJson(jsonFromRedis, HashMap.class);

        // Print the HashMap retrieved from Redis
        System.out.println(mapFromRedis);

        jedis.close();
    }
}


In this example, we first create a HashMap object and serialize it into a JSON string using the Gson library. Next, we store this JSON string in Redis with the key "myHashMap". Finally, we retrieve the JSON string from Redis, deserialize it back into a HashMap object, and print it out.