Spring Boot 自动配置 : RedisAutoConfiguration

概述

Spring Boot关于Spring Data Redis的自动配置类。该自动配置类检测到包spring-data-redis被使用时才应用。并且导入了另外两个配置类LettuceConnectionConfiguration,JedisConnectionConfiguration,这两个配置类是用于配置底层Redis连接组件RedisConnectionFactory,一种基于Lettuce Redis客户端实现,一种基于Jedis Redis客户端实现,不会同时生效。因为包spring-boot-starter-data-redis自身依赖lettuce,所以缺省情况下,LettuceConnectionConfiguration会生效,JedisConnectionConfiguration不生效。

RedisAutoConfiguration自身主要的作用是确保以下bean存在于容器中 :

  • RedisTemplate redisTemplate – 基于容器中的redisConnectionFactory bean
  • StringRedisTemplate stringRedisTemplate – 基于容器中的redisConnectionFactory bean

redisConnectionFactory beanLettuceConnectionConfiguration,JedisConnectionConfiguration或者其他方式定义。

源代码

源代码版本 : spring-boot-autoconfigure-2.1.3.RELEASE

package org.springframework.boot.autoconfigure.data.redis;

// 省略 import 行

/**
 * EnableAutoConfiguration Auto-configuration for Spring Data's Redis support.
 *
 */
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

    // 定义 bean RedisTemplate redisTemplate
	@Bean
    // 仅在该 bean 不存在的情况下才定义
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

    // 定义 bean StringRedisTemplate  stringRedisTemplate
	@Bean
      // 仅在该 bean 不存在的情况下才定义
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

}

你可能感兴趣的:(Spring,Boot,自动配置,Spring,Data,分析)