Detailed explanation of redis configuration based on spring of stand alone and cluster mode

  • 2021-07-01 07:21:28
  • OfStack

jar packages required: spring version: 4.3. 6. RELEASE, jedis version: 2.9. 0, spring-data-redis: 1.8. 0. RELEASE; Additional jackson-annotations and jackson-databind packages are required if jackson serialization is used

spring integrated redis stand-alone version:

1. Configure RedisTemplate


<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  <property name="connectionFactory" ref="connectionFactory"/>
   <property name="defaultSerializer" ref="stringRedisSerializer"/>
   <property name="keySerializer" ref="stringRedisSerializer"/>
   <property name="valueSerializer" ref="valueSerializer"/>
</bean>

2. Configure connectionFactory


    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
      <!--  Configure ip -->
      <property name="hostName" value="${redis.host}"/>
      <!--  Configure port -->
      <property name="port" value="${redis.port}"/>
      <!--  Whether to use connection pooling -->
      <property name="usePool" value="${redis.usePool}"/>
      <!--  Configure redis Connection pool -->
      <property name="poolConfig" ref="poolConfig"/>
    </bean>

3. Configure connection pooling


    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
      <!-- Maximum number of idle instances -->
      <property name="maxIdle" value="${redis.maxIdle}" />
      <!-- Maximum number of active instances -->
      <property name="maxTotal" value="${redis.maxTotal}" />
      <!-- Maximum wait time when creating an instance -->
      <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
      <!-- Whether to validate when creating an instance -->
      <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>

spring integrated redis cluster

1. Configure RedisTemplate steps to stand-alone version 1

2. Configure connectionFactory


    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
      <!--  Configure redis Connection pool -->  
      <constructor-arg ref="poolConfig"></constructor-arg>
      <!--  Configure redis Cluster --> 
     <constructor-arg ref="clusterConfig"></constructor-arg>
      <!--  Whether to use connection pooling -->
      <property name="usePool" value="${redis.usePool}"/>
    </bean>

3. Configure Connection Pool Steps and Stand-alone Version 1

4. Configure the redis cluster


    <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
      <property name="maxRedirects" value="3"></property>
      <property name="clusterNodes">
        <set>
          <bean class="org.springframework.data.redis.connection.RedisClusterNode">
            <constructor-arg value="${redis.host1}"></constructor-arg>
            <constructor-arg value="${redis.port1}"></constructor-arg>
          </bean>
          <bean class="org.springframework.data.redis.connection.RedisClusterNode">
            <constructor-arg value="${redis.host2}"></constructor-arg>
            <constructor-arg value="${redis.port2}"></constructor-arg>
          </bean>
          ......
        </set>
      </property>
    </bean

Or


    <bean name="propertySource" class="org.springframework.core.io.support.ResourcePropertySource">
      <constructor-arg name="location" value="classpath:properties/spring-redis-cluster.properties" />
    </bean>
    <bean id="clusterConfig" class="org.springframework.data.redis.connection.RedisClusterConfiguration">
      <constructor-arg name="propertySource" ref="propertySource"/>
    </bean>

Brief description of serialization configuration:

1. stringRedisSerializer: StringRedisSerializer is generally used because key of redis is String type

2. valueSerializer: For value serialization of redis, spring-data-redis provides a number of serialization classes. Jackson2JsonRedisSerializer is recommended here, and the default is JdkSerializationRedisSerializer

3. JdkSerializationRedisSerializer: Use the serialization capabilities provided by JDK. The advantage is that there is no need to provide type information when deserializing (class), but the disadvantage is that the serialized result is very large, which is about 5 times that of JSON format, which will consume a lot of memory of redis server.

4. Jackson2JsonRedisSerializer: Serialize an object into an JSON string using the Jackson library. The advantages are high speed and short and pithy serialized strings. But the drawback is also fatal, that is, there is one type parameter in the constructor of this class, which must provide the type information of the object to be serialized (. class object).

Use spring annotation to configure redis, where only cluster samples are configured


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

  //spring3 Support annotation method to obtain value  In application You can get the configuration file path in the 
  @Value("${spring.redis.cluster.nodes}")
  private String clusterNodes;

  @Value("${spring.redis.cluster.timeout}")
  private Long timeout;

  @Value("${spring.redis.cluster.max-redirects}")
  private int redirects;

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

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

  @Value("${redis.maxWaitMillis}")
  private long maxWaitMillis;

  @Value("${redis.testOnBorrow}")
  private boolean testOnBorrow;

  /**
   *  Select redis As the default caching tool 
   * @param redisTemplate
   * @return
   */
  @Bean
  public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    //cacheManager.setDefaultExpiration(60);
    //Map<String,Long> expiresMap=new HashMap<>();
    //expiresMap.put("redisCache",5L);
    //cacheManager.setExpires(expiresMap);
    return cacheManager;
  }

  @Bean
  public RedisClusterConfiguration redisClusterConfiguration(){
    Map<String, Object> source = new HashMap<>();
    source.put("spring.redis.cluster.nodes", clusterNodes);
    source.put("spring.redis.cluster.timeout", timeout);
    source.put("spring.redis.cluster.max-redirects", redirects);
    return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
  }

  @Bean
  public JedisConnectionFactory redisConnectionFactory(RedisClusterConfiguration configuration){
    JedisPoolConfig poolConfig = new JedisPoolConfig();
    poolConfig.setMaxIdle(maxIdle);
    poolConfig.setMaxTotal(maxTotal); 
    poolConfig.setMaxWaitMillis(maxWaitMillis);
    poolConfig.setTestOnBorrow(testOnBorrow);
    return new JedisConnectionFactory(configuration,poolConfig);
  }

  /**
   * retemplate Related configuration 
   * @param factory
   * @return
   */
  @Bean
  public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {

    RedisTemplate<String, Object> template = new RedisTemplate<>();
    //  Configure the connection factory 
    template.setConnectionFactory(factory);

    // Use Jackson2JsonRedisSerializer To serialize and deserialize redis Adj. value Value (used by default JDK How to serialize the) 
    Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

    ObjectMapper om = new ObjectMapper();
    //  Specifies the domain to serialize, field,get And set, And the range of modifiers, ANY Yes, it all includes private And public
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    //  Specifies the type of serialized input, and the class must be non- final Modified, final Modified classes, such as String,Integer Run out of anomaly later 
    //om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jacksonSeial.setObjectMapper(om);

    //  Value adopts json Serialization 
    template.setValueSerializer(jacksonSeial);
    // Use StringRedisSerializer To serialize and deserialize redis Adj. key Value 
    template.setKeySerializer(new StringRedisSerializer());

    //  Settings hash key  And value Serialization mode 
    template.setHashKeySerializer(new StringRedisSerializer());
  
    template.setHashValueSerializer(jacksonSeial);
    template.afterPropertiesSet();

    return template;
  }
}

Precautions:

1. Using annotated configuration redis or using @ Configuration requires specifying the configuration files under what packages to scan in the configuration files. Of course, if it is springboot, when I didn't say this...


<context:component-scan base-package="com.*"/>

2. spring3 supports annotation to obtain Value, but it needs to be loaded in the configuration file configuration file path, and the specific value is specified by yourself...


<value>classpath:properties/spring-redis-cluster.properties</value>

3. Since the original framework of our company adopts spring 2.5. 6, The main difference between spring2 and spring2 + (of course, I think it myself) is that each module is divided into different jar. For redis using spring-data-redis template processing, spring2.5. 6 and spring4 will not conflict in stand-alone case, However, if you need to configure redis cluster by using cluster mode, jar packet collision will occur. At this time, it depends on how to decide. You can directly use jedisCluster to connect redis cluster (but many methods need to be written by yourself), or you can replace spring 2.5. 6 with a higher version of spring4, but there are more things to pay attention to in framework replacement (there is nothing wrong with our company's direct full replacement, OK, O (φ _ φ) O haha ~), as for rewriting JedisConnectionFactory and RedisClusterConfiguration, I haven't tried yet, this can be used as a follow-up supplement...

4. By the way, ibatis is no longer supported by spring4. If you need to use spring4 and need to connect ibatis, the most rude way is to replace spring-orm package with spring3 version, and other jar is still version 4. (Of course, there is nothing wrong with replacing directly on my side, but there may be potential problems with the same type 31, so sometimes the company still needs to be updated...)


Related articles: