Why Getting NoClassDefFound error for JedisConnect

2019-05-14 04:40发布

问题:

Hello when trying to use spring-redis i am getting

java.lang.NoClassDefFoundError: Could not initialize class org.springframework.data.redis.connection.jedis.JedisConnection

exception when doing any connection operation using redis. My config method goes like this

 @Bean
public RedisConnectionFactory jedisConnFactory() {
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();

    jedisConnectionFactory.setHostName("XXX.XX.XX.XXX");

    jedisConnectionFactory.setPort(6381);
    jedisConnectionFactory.setUsePool(true);
    jedisConnectionFactory.afterPropertiesSet();
    return jedisConnectionFactory;

Please suggest if anyone knows why i am getting this exception.

回答1:

After wasting almost one day and finding that the jar is already on my class path, i further debugged it and found that when java's reflection mechanism was trying to find a method which was already present in the "methods list" it was not able to find due to some version conflict between Jedis version (2.7.2) not compatible with Spring Data Redis (1.5.0.RELEASE) , this issue has already been answered in this link ::
Jedis and spring data redis version conflict



回答2:

JedisPoolConfig is needed when we use Jedis Configuration. In Spring Boot 2.0, spring-boot-starter-data-redis gives Lettuce dependency by default instead of Jedis. To use Jedis configuration, exclude Lettuce and add Jedis as following.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>            
</dependency>        
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>


回答3:

The class org.springframework.data.redis.connection.jedis.JedisConnection is not in your classpath. Please check if you have this dependency available and if it's missing include it.

The missing jar should be, given your redis version, like this from Maven repository redis page, so in the form spring-data-redist-(your-version).jar



回答4:

Change to compatible version:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.0.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>