RedisTemplate switches Jedis implementations and common Jedis API s

Keywords: Java Redis Spring Boot

catalogue

RedisTemplate switch Jedis implementation

Switch the underlying Jedis API operation Redis

RedisTemplate switch Jedis implementation

1. Spring Boot is Lettuce and Jedis The client library provides basic automatic configuration. By default, it is used Lettuce As a client, if you want to switch the Jedis client, there are two steps:

1: Switch dependency: exclude the default lettuce dependency in spring boot starter data redis, and then introduce jedis dependency.

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

        <!--introduce jedis Dependence. Internal dependency  commons-pool2 Connection pool -->
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

II: Modify configuration : switch lettuce configuration to jedis configuration

#Redis configuration, except for timeout, is the default configuration
spring:
  redis:
    host: localhost
    port: 6379
    database: 2
    password:
    timeout: 10000
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

3: Switching principle

1. When the application starts, the org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration configuration class is automatically loaded.

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

2. If there is lettuce dependency in the application, the lettuce client will be used automatically. Similarly, if there is jedis dependency in the application, the jedis client will be used automatically.

  Demo source code: src/main/resources/application.yml · Wang Shaotang / wmx redis - gitee.com

Switch the underlying Jedis API operation Redis

1. RedisTemplate bottom layer supports lattice client (default) and Jedis client, while redis database can be deployed in a single machine or cluster. Different clients and deployment methods use different API s at the bottom layer.

Redistemplate (class)RedisTemplate has been automatically added to the container in RedisAutoConfiguration. You can get it directly for use
Stringredistemplate (class)Inherited from RedisTemplate, RedisAutoConfiguration has been added to the container when it is started, and can be obtained and used directly.
Redisconnectionfactory (Interface)

A thread safe connection factory used to obtain redis connections.

RedisAutoConfiguration has been added to the container when it is started, and can be obtained and used directly.

Jedisconnectionfactory (class)Redisconnectionfactory (Interface) is implemented
Lettueconnectionfactory (class)Redisconnectionfactory (Interface) is implemented
Redisconnection (Interface)

Connection to Redis server. It serves as a general abstraction for various Redis client libraries (or drivers).

With a connection, you can operate the redis database. There are many implementations. The following are commonly used.

Jedisconnection (class)Implement redisconnection (Interface)
Lettuceconnection (class)Implement redisconnection (Interface)
Redisclusterconnection (Interface)Inheriting redisconnection (Interface), distributed connection for redis cluster deployment
Jedisclusterconnection (class)Redisclusterconnection (Interface) is implemented
Lettueclusterconnection (class)Redisclusterconnection (Interface) is implemented

2. Direct is highly recommended Use RedisTemplate and StringRedisTemplate templates In this way, you no longer need to release or close the connection yourself, but only need to focus on the operation data. Interface oriented programming is preferred. Otherwise, once the underlying redis client is switched or the redis deployment mode is changed, the implementation code needs to be changed.

3. In actual development, you may want to use the underlying Jedis or lattice client API. For example, the upper RedisTemplate does not encapsulate some methods. These characteristic APIs are only available in the underlying Jedis or lattice.

    /**
     * Thread safe Redis connection factory, {@ link RedisAutoConfiguration} startup has been added to the container and can be obtained and used directly
     * RedisConnectionFactory RedisTemplate.getConnectionFactory(): RedisConnectionFactory connection factory can also be obtained
     */
    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    /**http://localhost:8080/jedis/getJedis
     * @return
     */
    @GetMapping("/jedis/getJedis")
    public Map<String, Object> getJedis() {
        Map<String, Object> resultMap = new HashMap<>(8);
        resultMap.put("code", 200);

        JedisConnection jedisConnection = null;
        try {
            /**
             * RedisConnectionFactory getRequiredConnectionFactory(): Get the ConnectionFactory connection factory. Throw an exception if it is not set
             * RedisConnection getConnection(RedisConnectionFactory factory): Obtain Redis connection from the factory
             * * 1,Returns any existing corresponding connection bound to the current thread, for example, when using the transaction manager, otherwise a new connection will always be created.
             * * 2,factory: Parameter factory used to create the connection
             * * 3,Returns an active Redis connection without transaction management
             * RedisConnection getConnection(RedisConnectionFactory factory, boolean enableTranactionSupport): Obtain Redis connection from the factory
             * * 1,enableTranactionSupport If true, the active Redis connection with transaction management is returned
             */
            jedisConnection = (JedisConnection) RedisConnectionUtils.getConnection(redisConnectionFactory, true);

            // With Jedis, you can use any of its methods to operate Redis
            Jedis jedis = jedisConnection.getNativeConnection();

            Set<String> keys = jedis.keys("*");
            resultMap.put("data", keys);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("msg", e.getMessage());
            resultMap.put("data", null);
        } finally {
            /**
             * releaseConnection(@Nullable RedisConnection conn, RedisConnectionFactory factory): Closes the given connection created through the given factory if it is not externally managed (i.e. not bound to a thread)
             * * conn: Redis connection to close.
             * * factory: Redis factory for creating connections
             */
            if (jedisConnection != null) {
                RedisConnectionUtils.releaseConnection(jedisConnection, redisConnectionFactory);
            }
        }
        return resultMap;
    }

Online demo source code: src/main/java/com/wmx/wmxredis/jedis/JedisController.java · Wang Shaotang / wmx redis - gitee.com

Posted by eldee on Sat, 27 Nov 2021 19:42:55 -0800