Search code examples
javajunitredis

Redis - JUnit - Caused by: java.net.UnknownHostException: localhost


I have a SpringBoot application where I connect to Redis and it works on cloud environment:

 RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
 redisStandaloneConfiguration.setHostName("localhost");
 redisStandaloneConfiguration.setPort(6379);
 redisStandaloneConfiguration.setPassword(REDIS_PASSWORD);
 LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
 lettuceConnectionFactory.setValidateConnection(true);

Now i started a local Redis instance on localhost and port 6379; I tried to write a Junit test that uses Redis and I got the following exception

Caused by: io.lettuce.core.RedisConnectionException: Unable to connect to  localhost:6379
    at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:78)
    at io.lettuce.core.RedisConnectionException.create(RedisConnectionException.java:56)
    at io.lettuce.core.AbstractRedisClient.getConnection(AbstractRedisClient.java:320)
    at io.lettuce.core.RedisClient.connect(RedisClient.java:211)
    at org.springframework.data.redis.connection.lettuce.StandaloneConnectionProvider.lambda$getConnection$1(StandaloneConnectionProvider.java:115)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.springframework.data.redis.connection.lettuce.StandaloneConnectionProvider.getConnection(StandaloneConnectionProvider.java:115)
    at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.getConnection(LettuceConnectionFactory.java:1459)
    ... 17 common frames omitted
Caused by: java.net.UnknownHostException:  localhost
    at java.net.InetAddress.getAllByName0(InetAddress.java:1281)
    at java.net.InetAddress.getAllByName(InetAddress.java:1193)
    at java.net.InetAddress.getAllByName(InetAddress.java:1127)
    at java.net.InetAddress.getByName(InetAddress.java:1077)

Any hints?

I tried:

  • localhost
  • 127.0.0.1
  • put localhost 127.0.0.1 in hosts file

But got the same exception


Solution

  • After some hours I found the problem:

    redis.cluster.nodes:${REDIS_CLUSTER_NODES: localhost:6379;}
    

    If I put

    redis.cluster.nodes: localhost:6379;
    

    it works fine