Java development must understand: Redis must know - basic summary

 

1. Some basic uses of Redis

Redis is a memory-based data storage system that can be used as a database, cache, message queue, and many other purposes. The following are some basic usage methods of Redis:

  1. Install Redis: You can download the installation package from the official website of Redis and install it, or use the package management tool to install it.

  2. Start Redis: Enter the redis-server command in the terminal to start the Redis server. If no configuration file is specified, the default configuration will be used.

  3. Connect to Redis: You can use the redis-cli command to connect to the Redis server.

  4. Storing and obtaining data: You can use the set, get and other commands provided by Redis to store and obtain data. For example:

    > set mykey "Hello Redis"
    OK
    > get mykey
    "Hello Redis"
    

  5. Expiration time: The expiration time can be set for the stored data. For example:
> set mykey "Hello Redis" EX 3600
OK

         The above command will set the expiration time of mykey to 3600 seconds.

    6. Data types: Redis supports a variety of data types, including strings, lists, sets, ordered sets, and hash tables. Different data types can be selected according to different usage scenarios.

    7. Publish and subscribe messages: You can use the publish and subscribe commands provided by Redis to implement the function of publishing and subscribing messages.

   8. Cluster: If you need to share data and load balance among multiple Redis nodes, you can use Redis cluster to achieve it. Redis cluster can automatically distribute data to different nodes, and supports functions such as failover and automatic expansion.

2. Commonly used methods in Redis:

Redis is a feature-rich in-memory data storage system that provides a wealth of commands and methods to manipulate data. The following are commonly used methods in Redis:

  1. key-value operations
  • SET: set key-value pair
  • GET: Get the value of the key-value pair
  • DEL: Delete a key-value pair
  • EXISTS: Determine whether the key exists
  • INCR: Increment the value corresponding to the key by 1
  • DECR: Decrease the value corresponding to the key by 1
  1. list manipulation
  • LPUSH: Insert one or more values ​​at the head of the list
  • RPUSH: Insert one or more values ​​at the end of the list
  • LPOP: pop a value from the head of the list
  • RPOP: pop a value from the end of the list
  • LLEN: get the length of the list
  1. set operation
  • SADD: Add one or more elements to a collection
  • SMEMBERS: Get all the elements in the collection
  • SISMEMBER: determine whether the element is in the set
  • SREM: remove one or more elements from a collection
  • SCARD: Get the number of elements in the collection
  1. sorted set operations
  • ZADD: Add one or more elements to an ordered set
  • ZRANGE: Get elements within a specified range in an ordered collection
  • ZREVRANGE: Get the elements within the specified range in the ordered collection, sorted according to the score from large to small
  • ZRANK: Get the rank of elements in an ordered set
  • ZSCORE: Get the score of an element in an ordered set
  1. hash table operations
  • HSET: Add a key-value pair to the hash table
  • HGET: Get the value of the specified key in the hash table
  • HDEL: Delete one or more key-value pairs in a hash table
  • HGETALL: Get all key-value pairs in the hash table
  • HLEN: Get the number of key-value pairs in the hash table
  1. other operations
  • PUBLISH: Publish the message to the specified channel
  • SUBSCRIBE: Subscribe to the specified channel
  • UNSUBSCRIBE: Unsubscribe from the specified channel

These are commonly used methods in Redis. For more detailed methods, please refer to the official documentation of Redis.

3. Data types in Redis

Redis supports multiple data types, and each type has its own characteristics and applicable scenarios. The following are commonly used data types in Redis:

  1. String (string) String is the most basic data type in Redis, which can store any type of data, such as text, numbers, binary data, etc. The operations supported by the string type include setting value, getting value, increasing and decreasing value, setting expiration time, etc.

  2. List (list) List is an ordered list of strings, you can add, delete, insert, find and modify elements in the list. The operations supported by the list type include adding or removing elements from the head or tail of the list, obtaining the length of the list, obtaining elements in a specified range, and so on.

  3. Set (set) A set is an unordered set of unique elements that supports operations such as adding, deleting, and finding elements. The operations supported by the collection type include adding elements to the collection, removing elements from the collection, getting all elements in the collection, and so on.

  4. Sorted set (sorted set) An ordered set is an ordered and unique list of elements, each element is associated with a score, and supports sorting and querying elements by score. The operations supported by the ordered collection type include adding elements to the ordered collection, obtaining elements in a specified range according to the score, obtaining the score of the element according to the member, etc.

  5. Hash table (hash) A hash table is a collection of key-value pairs, each key corresponds to a value. The operations supported by the hash table type include adding, deleting, obtaining, and updating key-value pairs.

  6. Other data types Redis also supports some other data types, such as bitmaps (bitmaps), geographic location (geospatial), and so on. These data types have their own characteristics and usage scenarios.

These are commonly used data types in Redis, and each data type has its own applicable scenarios. According to specific usage requirements, different data types can be selected to store data.

4. Specific instructions for using Redis in SpringBoot

To use Redis in Spring Boot, you need to add corresponding dependencies, and then configure Redis connection information and RedisTemplate instances. The following is a sample code for connecting to Redis and operating Redis using Spring Boot:

1. Add Redis dependency

Add the following Redis-related dependencies to the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Configure Redis connection information

Add Redis connection information in the application.properties file:

Connection timeout cannot be empty

spring.redis.host=localhost
spring.redis.port=6379
# redis访问密码(默认为空)
spring.redis.password=
# redis连接超时时间(单位为毫秒)
spring.redis.timeout=5000

Add Redis connection information in the bootstrap.yml file:

  redis:
    # redis数据库索引(默认为0),我们使用索引为3的数据库,避免和其他数据库冲突
    database: 3
    # redis服务器地址(默认为localhost)
    host: localhost
    # redis端口(默认为6379)
    port: 6379
    # redis访问密码(默认为空)
    # password: 
    # redis连接超时时间(单位为毫秒)
    timeout: 5000
    # redis连接池配置
    pool:
    # 最大可用连接数(默认为8,负数表示无限)
    max-active: 8
    # 最大空闲连接数(默认为8,负数表示无限)
    max-idle: 8
    # 最小空闲连接数(默认为0,该值只有为正数才有作用)
    min-idle: 0
    # 从连接池中获取连接最大等待时间(默认为-1,单位为毫秒,负数表示无限)
    max-wait: -1

3. Configure the RedisTemplate instance

The first configuration method:

Configure the RedisTemplate instance in the configuration class. You can choose to use the default RedisTemplate instance or customize the RedisTemplate instance. The sample code is as follows:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //初始化RedisTemplate
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

redisTemplate.afterPropertiesSet() description:

redisTemplate.afterPropertiesSet()Is a method in the Spring Data Redis framework, used to configure and initialize a RedisTemplate instance.

In Spring, beans are typically created and configured through XML or Java configuration files. When the Spring container creates a bean, it injects any necessary dependencies, then invokes methods afterPropertiesSet()to give the bean a chance to perform any additional initialization tasks.

For RedisTemplate, calling this afterPropertiesSet()method is important because it sets up the template's connection factory and Redis serializer. These properties can be configured in Spring configuration files or via the RedisTemplate API.

To sum up, invoking redisTemplate.afterPropertiesSet()is a necessary step to initialize and configure the RedisTemplate instance in Spring Data Redis.

RedisConnectionFactory description:

There are several implementations of RedisConnectionFactory that provide different ways to create Redis connections, including LettuceConnectionFactory, JedisConnectionFactory, and RedissonConnectionFactory. These implementations use different Redis client libraries and provide different configuration options.

To use RedisConnectionFactory in a Spring application, create a bean of appropriate RedisConnectionFactory implementation and configure it with the necessary Redis server connection details such as Redis host and port. You can also customize the connection factory by setting options such as connection timeout, pool configuration, and SSL encryption.

Once the RedisConnectionFactory bean is created, you can use it to create a RedisTemplate instance by passing it as a parameter to the RedisTemplate constructor or by setting it through a method setConnectionFactory. RedisTemplate provides convenient methods for interacting with Redis data structures, such as hash operations, list operations, and set operations.

To sum up, RedisConnectionFactory is an interface provided by Spring Data Redis, which defines the contract for creating Redis connections. It has several implementations that provide different ways to connect to a Redis server, and can be configured and customized to meet the requirements of a Spring Redis application.

The second configuration method:



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;
import java.io.Serializable;


@Configuration
public class RedisConfiguration {
    @Resource
    private LettuceConnectionFactory myLettuceConnectionFactory;
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate() {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(myLettuceConnectionFactory);
        return template;
    }
}

LettuceConnectionFactory Description: 

LettuceConnectionFactory is a class in the Spring Data Redis framework that provides a connection factory for creating Redis connections using the Lettuce Redis client library. It implements the RedisConnectionFactory interface and can be used with RedisTemplate to connect to and interact with a Redis server.

Lettuce is a high-performance and scalable Redis client library written in Java. It supports advanced features such as connection pooling, thread safety, and reactive programming, making it a popular choice for high-performance Redis applications.

To use LettuceConnectionFactory in a Spring application , you first need to create a bean of type LettuceConnectionFactory and configure it with the necessary Redis server connection details such as Redis host and port. You can also customize the connection factory by setting options such as connection timeout, pool configuration, and SSL encryption.

Once the LettuceConnectionFactory bean is created, it can be used to create a RedisTemplate instance by passing it as a parameter to the RedisTemplate constructor or by setting it through a method setConnectionFactory. RedisTemplate provides convenient methods for interacting with Redis data structures, such as hash operations, list operations, and set operations.

To sum up, LettuceConnectionFactory is a connection factory provided by Spring Data Redis, which uses the Lettuce Redis client library to create a Redis connection. It can be configured and customized to meet the requirements of a Spring Redis application.

4. Use RedisTemplate instance to operate Redis

Use the RedisTemplate instance to operate Redis in the service class. The following is a simple sample code:



import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtils {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key,long time){
        try {
            if(time>0){
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String ... key){
        if(key!=null&&key.length>0){
            if(key.length==1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key,Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key,Object value,long time){
        try {
            if(time>0){
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            }else{
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta){
        if(delta<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    //================================Map=================================
    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key,String item){
        HashOperations<String, Object, Object> operations =redisTemplate.opsForHash();
         List<Object> reslutMapList =operations.values(key);
        Set<Object> resultSetList=operations.keys(key);
        if (StringUtils.isEmpty(operations.toString())){
            return null;
        }
        return operations.get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object,Object> hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String,Object> map){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String,Object> map, long time){
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key,String item,Object value,long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if(time>0){
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item){
        redisTemplate.opsForHash().delete(key,item);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item){
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key 键
     * @param item 项
     * @param by 要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     * @param key 键
     * @param item 项
     * @param by 要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item,double by){
        return redisTemplate.opsForHash().increment(key, item,-by);
    }

    //============================set=============================
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key){
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key,Object value){
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object...values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key,long time,Object...values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if(time>0) expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object ...values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    //===============================list=================================

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end){
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
    public long lGetListSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index,Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key,long count,Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}

5. Enable Redis Cluster



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.util.HashMap;
import java.util.Map;

@ConditionalOnProperty(prefix="",name = "spring.redis.cluster", havingValue = "true")
public class RedisFactoryConfig {
  @Autowired
  private Environment environment;
  @Bean
  public RedisConnectionFactory myLettuceConnectionFactory() {
    Map<String, Object> source = new HashMap<String, Object>();
    source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes"));
source.put("spring.redis.cluster.timeout", environment.getProperty("spring.redis.cluster.timeout"));
    source.put("spring.redis.cluster.timeout","5000");
// 配置集群的最大重定向次数
    source.put("spring.redis.cluster.max-redirects", 
environment.getProperty("spring.redis.cluster.max-redirects"));
    RedisClusterConfiguration redisClusterConfiguration;
    redisClusterConfiguration = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
    return new LettuceConnectionFactory(redisClusterConfiguration);
  }
}

@ConditionalOnProperty description: 

@ConditionalOnProperty is a Spring Framework annotation that allows developers to conditionally enable or disable certain parts of the application configuration based on the presence or absence of specified properties in the application environment.

This annotation can be used to configure a bean, a component, or an entire configuration class based on the value of one or more properties. For example, if an application requires a specific database connection, but it can also fall back to a default configuration if the required property is not present,@ ConditionalOnProperty can be used to determine which configuration should be used based on the properties set.

Annotations take one or more property names as parameters, and optional values ​​for those properties. An annotated component or configuration class is included in the application's context if one or more properties exist in the application's environment and their values ​​match the specified value (if any). Otherwise, it will be excluded.

@ConditionalOnProperty(prefix="",name = "spring.redis.cluster", havingValue = "true")具体说明: 

@ConditionalOnPropertyIt is a conditional annotation provided by the Spring framework, which can determine whether to create a bean according to the specified attribute value. Specifically, @ConditionalOnPropertythe annotation checks the specified property value, and if the condition is met, a bean is created; otherwise, the bean is not created.

@ConditionalOnPropertyAnnotations have three main properties:

  • prefix: Prefix for attributes.
  • name: The name of the attribute.
  • havingValue: The value of the attribute.

Among them, prefixthe and nameattribute are used to specify the attribute to be checked, and havingValuethe attribute is used to specify the value of the attribute to be checked.

Therefore, @ConditionalOnProperty(prefix="",name = "spring.redis.cluster", havingValue = "true")it means that the bean marked by this annotation will only be created when the attribute value application.propertiesin the configuration file is . The attribute in this annotation is empty, indicating that no prefix is ​​required.spring.redis.clustertrueprefix

In Spring Boot, @ConditionalOnPropertyannotations are often used to create beans based on property values ​​in configuration files. For example, when configuring a Redis cluster, you can spring.redis.clusterdecide whether to create a connection pool based on the value of the attribute. If spring.redis.clusterso true, create a Redis cluster connection pool; otherwise, create a single-node Redis connection pool.

Principle first, then code, practice while learning. The principle is used to guide the focus of code reading

Guess you like

Origin blog.csdn.net/qq_45656077/article/details/129708454