Skip to content

How to resolve IllegalArgumentException: Host must not be empty when using spring boot data redis and lettuce?

1. Purpose

In this post, I will demo how to solve the below exception or error when using spring boot data redis and lettuce:

Terminal window
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
2021-03-21 15:27:30.705 INFO 61218 --- [ Test worker] c.bswen.app10.service.TestRedisService : Starting TestRedisService using Java 1.8.0_121 on MBP-bswen with PID 61218 (started by bswen in /Users/bswen/private/bw/bswen-github/bswen-springboot23/app10)
2021-03-21 15:27:32.011 WARN 61218 --- [ Test worker] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisService': Unsatisfied dependency expressed through field 'redisClient'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisClient' defined in class path resource [com/bswen/app10/config/RedisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.RedisClient]: Factory method 'redisClient' threw exception; nested exception is java.lang.IllegalArgumentException: Host must not be empty
2021-03-21 15:27:32.035 INFO 61218 --- [ Test worker] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-03-21 15:27:32.088 ERROR 61218 --- [ Test worker] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisService': Unsatisfied dependency expressed through field 'redisClient'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisClient' defined in class path resource [com/bswen/app10/config/RedisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.RedisClient]: Factory method 'redisClient' threw exception; nested exception is java.lang.IllegalArgumentException: Host must not be empty
Caused by: java.lang.IllegalArgumentException: Host must not be empty
at io.lettuce.core.internal.LettuceAssert.notEmpty(LettuceAssert.java:44) ~[lettuce-core-6.0.2.RELEASE.jar:6.0.2.RELEASE]
at io.lettuce.core.RedisURI$Builder.redis(RedisURI.java:1151) ~[lettuce-core-6.0.2.RELEASE.jar:6.0.2.RELEASE]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisClient' defined in class path resource [com/bswen/app10/config/RedisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.RedisClient]: Factory method 'redisClient' threw exception; nested exception is java.lang.IllegalArgumentException: Host must not be empty
... 122 more
Caused by: java.lang.IllegalArgumentException: Host must not be empty
at io.lettuce.core.internal.LettuceAssert.notEmpty(LettuceAssert.java:44)
* What went wrong:
Execution failed for task ':app10:test'.
> There were failing tests. See the results at: file:///Users/bswen/private/bw/bswen-github/bswen-springboot23/app10/build/test-results/test/
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 8s
6 actionable tasks: 5 executed, 1 up-to-date

The core exception is :

Terminal window
[com/bswen/app10/config/RedisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.RedisClient]: Factory method 'redisClient' threw exception; nested exception is java.lang.IllegalArgumentException: Host must not be empty
... 122 more
Caused by: java.lang.IllegalArgumentException: Host must not be empty
at io.lettuce.core.internal.LettuceAssert.notEmpty(LettuceAssert.java:44)
at io.lettuce.core.RedisURI$Builder.redis(RedisURI.java:1151)
at com.bswen.app10.config.RedisConfiguration.redisClient(RedisConfiguration.java:17)
at

2. The Environment

  • Jdk 8+
  • Spring boot 2.4+
  • Gradle 6.x+

3. The code and solution

3.1 The project structure

The project’s main package is com.bswen.app10, its main purpose is to connect to a redis server and do some unit tests.

└── src
├── main
│   ├── java
│   │   └── com
│   │   └── bswen
│   │   └── app10
│   │   ├── RedisApplication.java
│   │   ├── config
│   │   │   └── RedisConfiguration.java
│   │   ├── domain
│   │   │   └── SyncCommandCallback.java
│   │   └── service
│   │   └── RedisService.java
│   └── resources
│   ├── application-dev.properties
│   └── application.properties
└── test
├── java
│   └── com
│   └── bswen
│   └── app10
│   ├── package-info.java
│   └── service
│   └── TestRedisService.java
└── resources
└── application-test.properties

3.2 The project’s dependency

Let’s see the project’s gradle dependencies:

build.gradle
plugins {
id 'org.springframework.boot' version '2.4.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation('org.springframework.boot:spring-boot-starter-data-redis')
implementation 'io.lettuce:lettuce-core'
implementation 'org.apache.commons:commons-pool2'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
// exclude vintage, because we only use junit5
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
// specify the test profile , spring boot would try to load application-test.properties when testing
systemProperty 'spring.profiles.active', 'test'
useJUnitPlatform()
reports {
junitXml.enabled = true
html.enabled = false
}
}

You can see that we are using spring boot v2.4.2, and we are using spring-boot-starter-redis with lettuce, which is the default connector. we added lettuce-core as redis connection manager.

3.3 The configuration class

We need a configuration class to configure the redis connection.

RedisConfiguration.java
package com.bswen.app10.config;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("spring.redis")
public class RedisConfiguration {
private String host;
private int port;
@Bean
RedisClient redisClient() {
RedisURI uri = RedisURI.Builder.redis(this.host, this.port)
.build();
return RedisClient.create(uri);
}
}

In the above code, we define two fields(host and post) to construct the redisURI , which would be used by Lettuce RedisClient to create the redis connection.

3.4 The configuration file

We have specified the test profile when doing unit testing. So, the src/test/resources/application-test.properties file’s content is as follows:

src/test/resources/application-test.properties
spring.redis.host=2.3.4.7
spring.redis.port=6379

3.5 The test class

This is the test code:

TestRedisService.java
package com.bswen.app10.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TestRedisService {
@Autowired
private RedisService redisService;
@Test
public void testGetAndSet() {
redisService.set("hello","world");
Assertions.assertEquals(redisService.get("hello"),"world");
}
}

We just put a key/value to redis and then get the value with the same key, the assertion should be true.

3.6 Run the code

When we run the above test with gradle, we get this exception:

Terminal window
[com/bswen/app10/config/RedisConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.lettuce.core.RedisClient]: Factory method 'redisClient' threw exception; nested exception is java.lang.IllegalArgumentException: Host must not be empty
... 122 more
Caused by: java.lang.IllegalArgumentException: Host must not be empty
at io.lettuce.core.internal.LettuceAssert.notEmpty(LettuceAssert.java:44)
at io.lettuce.core.RedisURI$Builder.redis(RedisURI.java:1151)

why?

3.7 The reason

The reason for this error is as follows:

  • The lettuce RedisURI$Builder can not find the host of the redis
  • The host is configured in our RedisConfiguration, but the host field does not have getter and setter to access it

3.8 The solution

So the solution is easy, just add getter/setter to our RedisConfiguration class, just as follows:

RedisConfiguration.java
package com.bswen.app10.config;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties("spring.redis")
public class RedisConfiguration {
private String host;
private int port;
@Bean
RedisClient redisClient() {
RedisURI uri = RedisURI.Builder.redis(this.host, this.port)
.build();
return RedisClient.create(uri);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}

3.9 Re-run the test

Terminal window
Testing started at 15:31 ...
> Task :app10:cleanTest
> Task :app10:compileJava
> Task :app10:test
15:31:08.196 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
2021-03-21 15:31:08.996 INFO 61274 --- [ Test worker] c.bswen.app10.service.TestRedisService : Starting TestRedisService using Java 1.8.0_121 on MBP-bswen with PID 61274 (started by bswen in /Users/bswen/private/bw/bswen-github/bswen-springboot23/app10)
BUILD SUCCESSFUL in 8s
6 actionable tasks: 3 executed, 3 up-to-date
15:31:13: Tasks execution finished ':app10:cleanTest :app10:test --tests "com.bswen.app10.service.TestRedisService"'.

It works!

5. Summary

In this post, we demonstrated how to solve the IllegalArgumentException: Host must not be empty problem when using lettuce with springboot data redis, you can see that we should provide appropriate configurations to lettuce to construct the connection from lettuce to redis server. Thanks for your reading. Regards.

Final Words + More Resources

My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!