概述
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 bean
由LettuceConnectionConfiguration
,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;
}
}