Search code examples
javaredislettuce

Save Array or List of values to Redis cache


I'm attemptign to use Redis cloud and push an Array of String values using below code:

import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.RedisURI;
import com.lambdaworks.redis.api.StatefulRedisConnection;
import com.lambdaworks.redis.api.sync.RedisCommands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class WriteToRedis {

    private static final Logger logger = LoggerFactory.getLogger(ExchangeCurrencyPairScenario.class);

    public static void main(String[] args) throws JsonProcessingException {

        RedisClient redisClient = new RedisClient(
                RedisURI.create("redis://****@cloud.redislabs.com:15162"));
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        System.out.println("Connected to Redis");
        RedisCommands<String, String> syncCommands = connection.sync();
        syncCommands.rpush("key" , new String[]{"Volvo", "BMW", "Ford", "Mazda"});
        connection.close();
        redisClient.shutdown();
}

But receive exception:

Exception in thread "main" com.lambdaworks.redis.RedisCommandExecutionException: WRONGTYPE Operation against a key holding the wrong kind of value
    at com.lambdaworks.redis.LettuceFutures.await(LettuceFutures.java:127)
    at com.lambdaworks.redis.LettuceFutures.awaitOrCancel(LettuceFutures.java:96)
    at com.lambdaworks.redis.FutureSyncInvocationHandler.handleInvocation(FutureSyncInvocationHandler.java:61)
    at com.lambdaworks.redis.internal.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:80)
    at com.sun.proxy.$Proxy0.rpush(Unknown Source)
    at com.reactive.api.redis.WriteToRedis.main(WriteToRedis.java:39)

I can save String values and connect to the Redis cloud cache with no issue. But it seems I have not configured the format of the value associated with the "key" correctly? How to correctly persist and Array (or List) of values to a Redis cache using Java?


Solution

  • Redis operates by data types.

    Use of rpush in your code implies that you're trying to use RPUSH command which is part of List data type.

    You're trying to operate on a key named key and getting following error:

    WRONGTYPE Operation against a key holding the wrong kind of value
    

    Which means your Redis instance/DB already contains data in key key and the data type of existing data is something other than List.

    If you want to know the data type of data contained against a key, you can use TYPE command. E.g. to check key key:

    syncCommands.type("key");
    

    You can use DEL command to delete that data. E.g.

    syncCommands.del("key");