SpringBoot Chapter Integrating Jedis, Lettuce, and Redisson

Directory

  • Preface
  • 1. Detailed explanation of the differences between Jedis, Lettuce and Redisson
  • 2. SpringBoot integration
    • 2.1 Integrating Jedis
    • 2.2 Integrating Lettuce
    • 2.3 Integrating Redisson
  • Summarize

Foreword

Hello everyone, I am AK. I am working on a new project recently, which is based on the modification of the old project framework. I also happen to be sorting out springboot related knowledge recently. Redis is used in the project, so I sorted it out to help friends in need figure out which Redis client to choose. end library.

1. Detailed explanation of the differences between Jedis, Lettuce and Redisson

Jedis, Lettuce, and Redisson are all client libraries in Java that interact with the Redis database. They each have their own characteristics and uses.

1. Jedis:

Jedis is a commonly used Redis client that interacts with the database by directly operating Redis commands.
Jedis is single-threaded, meaning it can only handle one command request at a time. This makes it very efficient in a single-threaded environment and suitable for situations where there are few concurrent requests.
Jedis is simple to use, lightweight, and easy to get started with.

2. Lettuce:

Lettuce is an asynchronous, event-driven Redis client.
Lettuce is implemented based on the Netty framework. It uses an asynchronous non-blocking method to communicate with Redis and supports connection pooling and publish/subscribe modes.
Lettuce supports automatic management of concurrent requests and connections, and is suitable for handling high-concurrency environments.
Lettuce provides more configuration options and support for Redis features.

3. Redisson:

Redisson is a Redis client and data structure library based on Lettuce and Netty, providing rich distributed and clustering functions.
Redisson provides a higher level of abstraction, making it easier for developers to use Redis’s distributed locks, distributed collections, distributed queues and other functions.
Redisson supports cluster mode, master-slave replication and sentinel mode, and provides many distributed solutions and optimized data structures.
In terms of performance, Jedis and Lettuce may perform differently in different scenarios. Since Jedis is single-threaded, it is suitable for very low concurrency environments. Lettuce can better support high-concurrency environments through its asynchronous and non-blocking network processing method. Redisson is similar to Lettuce in terms of performance, but it focuses more on the operation of distributed functions and data structures.

In summary, Jedis is a simple and lightweight Redis client, suitable for low concurrency scenarios in a single-threaded environment; Lettuce is an asynchronous, event-driven Redis client, suitable for high concurrency scenarios, and provides more Multiple configuration options and function support; Redisson is a Redis client and data structure library based on Lettuce and Netty, providing rich distributed and cluster functions, and focusing on the optimization of distributed solutions and data structures. When choosing a suitable client, comprehensive considerations need to be made based on specific needs, scenarios, and performance requirements.

2. SpringBoot integration

2.1 Integrating Jedis

To integrate Jedis in Spring Boot, you can follow these steps:

Add dependencies: Open the project’s pom.xml file and add Jedis dependencies. You can add the following code under the tag:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.11.0</version>
</dependency>

Configure the Redis connection: In the Spring Boot configuration file (application.properties or application.yml), add the Redis connection configuration, including host, port, password, etc. For example, in the application.properties file, you can add the following code:

Redis connection configuration

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your_password (if you have a password)

Create Jedis instances: In Java code, you can create Jedis instances to interact with Redis. You can obtain a Jedis instance by injecting a JedisPool object into the class you need to use and using it. The sample code is as follows:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {<!-- -->

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisPool jedisPool() {<!-- -->
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);

        JedisPool jedisPool = new JedisPool(poolConfig, redisProperties.getHost(), redisProperties.getPort(), redisProperties.getTimeout(), redisProperties.getPassword());

        return jedisPool;
    }

    @Bean
    public Jedis jedis(JedisPool jedisPool) {<!-- -->
        return jedisPool.getResource();
    }
}

Here is an example of a Redis configuration class. You can configure it according to your needs and inject Jedis objects where you need to use Jedis.

Operations with Jedis: You can now use injected Jedis objects in other classes to perform Redis operations. You can execute various Redis commands by calling the methods provided by the Jedis object. Here’s a simple example:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class RedisService {<!-- -->

    @Autowired
    private Jedis jedis;

    public void set(String key, String value) {<!-- -->
        jedis.set(key, value);
    }

    public String get(String key) {<!-- -->
        return jedis.get(key);
    }
}

In the above example, we inject the Jedis object and use the set and get methods to set and get Redis.

In this way, you have successfully integrated Jedis into Spring Boot. You can perform more operations and configurations according to your needs. Remember to properly close Jedis connections and release resources when finished.

2.2 Integrating Lettuce

To integrate Lettuce in Spring Boot, you can follow these steps:

Add dependencies: Open the project’s pom.xml file and add Lettuce’s dependencies. You can add the following code under the tag:

<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.1.3.RELEASE</version>
</dependency>

Configure the Redis connection: In the Spring Boot configuration file (application.properties or application.yml), add the Redis connection configuration, including host, port, password, etc. For example, in the application.properties file, you can add the following code:

Redis connection configuration

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your_password (if you have a password)
spring.redis.lettuce.pool.max-active=10
Create a Lettuce instance: In code that needs to use Redis, you can use LettuceConnectionFactory to create a Lettuce connection factory and configure the connection pool. The sample code is as follows:
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

@Configuration
public class RedisConfig {<!-- -->

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.lettuce.pool.max-active}")
    private int maxActive;

    @Autowired(required = false)
    private ClientResources clientResources;

    @Bean(destroyMethod = "shutdown")
    public ClientResources clientResources() {<!-- -->
        return DefaultClientResources.create();
    }

    @Bean
    public RedisConnectionFactory lettuceConnectionFactory() {<!-- -->
        RedisURI redisURI = RedisURI.builder()
                .withHost(this.host)
                .withPort(this.port)
                .withPassword(this.password)
                .build();

        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                .clientResources(this.clientResources)
                .poolConfig(getDefaultPoolConfig())
                .build();

        RedisClient redisClient = RedisClient.create(redisURI);
        LettuceClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(getDefaultPoolConfig())
                .commandTimeout(redisClient.getOptions().getTimeout())
                .build();
        
        LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClient, lettucePoolingClientConfiguration);
        factory.setShareNativeConnection(false);

        return factory;
    }

    private GenericObjectPoolConfig<?> getDefaultPoolConfig() {<!-- -->
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(this.maxActive);
        return config;
    }
}

In the above example, we configured Lettuce’s connection and connection pool through LettucePoolingClientConfiguration and RedisURI. Where you need to use Redis, just inject the RedisConnectionFactory object.

Operations with Lettuce: You can now use injected RedisConnectionFactory objects in other classes to perform Redis operations. Spring Boot provides various RedisTemplate as the default Redis operation template, and you can also use ReactiveRedisTemplate for reactive operations. Here’s a simple example:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {<!-- -->

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void set(String key, String value) {<!-- -->
        redisTemplate.opsForValue().set(key, value);
    }

    public String get(String key) {<!-- -->
        return redisTemplate.opsForValue().get(key);
    }
}

In the above example, we injected the RedisTemplate object and used it to perform Redis set and get operations.

In this way, you have successfully integrated Lettuce into Spring Boot. You can perform more operations and configurations according to your needs. Remember to properly close the Redis connection and release resources when finished.

2.3 Integrating Redisson

To integrate Redisson in Spring Boot, you can follow these steps:

Add dependencies: Open the project’s pom.xml file and add Redisson’s dependencies. You can add the following code under the tag:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.16.1</version>
</dependency>

Configure Redisson: In the Spring Boot configuration file (application.properties or application.yml), add the Redisson configuration. For example, in the application.properties file, you can add the following code:

Redisson configuration

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your_password (if you have a password)

Operations with Redisson: You can inject a RedissonClient object in code that needs to use Redis and use it to perform Redis operations. Here’s a simple example:

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedisService {<!-- -->

    @Autowired
    private RedissonClient redissonClient;

    public void set(String key, String value) {<!-- -->
        redissonClient.getBucket(key).set(value);
    }

    public String get(String key) {<!-- -->
        return (String) redissonClient.getBucket(key).get();
    }
}

In the above example, we injected the RedissonClient object and used it to perform Redis set and get operations.

In this way, you have successfully integrated Redisson into Spring Boot. Redisson provides a variety of powerful APIs, and you can perform more operations and configurations according to your needs. Remember to properly close the Redis connection and release resources when finished.

Summary

In the end, if you still don’t know which one to choose, it is recommended to use Lettuce or Redisson. If it is a single application, choose Lettuce, and in a distributed scenario, choose Redisson.

—- Eternal number: I am AK