我通过 bean 名称定义它并使用 @Qulifier 注释。但它发送以下消息
@Configuration
public class RedisConfig {
@Value("${spring.redis.session.host}")
private String host;
@Value("${spring.redis.session.port}")
private int sessionPort;
@Bean(name = "redisSessionConnectionFactory")
public RedisConnectionFactory redisSessionConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(host);
configuration.setPort(sessionPort);
return new LettuceConnectionFactory(configuration);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(@Qualifier(value = "redisSessionConnectionFactory") RedisConnectionFactory redisSessionConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(redisSessionConnectionFactory);
return redisTemplate;
}
}
@Configuration
public class CacheConfig {
@Value("${spring.redis.cache.host}")
private String cacheHost;
@Value("${spring.redis.cache.port}")
private int cachePort;
@Bean(name = "redisCacheConnectionFactory")
public RedisConnectionFactory redisCacheConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(cacheHost);
configuration.setPort(cachePort);
return new LettuceConnectionFactory(configuration);
}
@Bean
public RedisCacheManager cacheManager(@Qualifier(value = "redisCacheConnectionFactory") RedisConnectionFactory redisCacheConnectionFactory) {
RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
Map<String, RedisCacheConfiguration> redisCacheConfigMap = new HashMap<>();
redisCacheConfigMap.put("board", defaultConfig.entryTtl(Duration.ofHours(1)));
redisCacheConfigMap.put("user", defaultConfig.entryTtl(Duration.ofSeconds(30L)));
RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisCacheConnectionFactory)
.withInitialCacheConfigurations(redisCacheConfigMap)
.build();
return redisCacheManager;
}
}
错误信息
Parameter 1 of method sessionRepositoryFilterRegistration in org.springframework.boot.autoconfigure.session.SessionRepositoryFilterConfiguration required a single bean, but 2 were found:
- redisCacheConnectionFactory: defined by method 'redisCacheConnectionFactory' in class path resource [com/cwg/test/config/CacheConfig.class]
- redisSessionConnectionFactory: defined by method 'redisSessionConnectionFactory' in class path resource [com/cwg/test/config/RedisConfig.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed