@Configuration
@ConditionalOnProperty(prefix = "xxl.job", name = "enable", havingValue = "true", matchIfMissing = true)
public class XxlJobConfig {
// ...
}
上述可直接读取配置文件中的,xxl.job.enable = true
@ConditionalOnProperty(prefix = "redis", name = "cluster", havingValue = "true")
ConditionalOnProperty注解中的 cluster 和 havingValue 指定的值一致时生效。
其中name="cluster"中的 cluster为当前对象中的属性
当然也可以不使用 @ConditionalOnProperty 中的name。
redis.cluster=false
private static boolean cluster;
@Value("${redis.cluster}")
public void setCluster(boolean c) {
cluster = c;
}
@Bean
@ConditionalOnProperty(prefix = "redis", name = "cluster", havingValue = "false")
public RedisTemplate<?, ?> redisTemplateSingle() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName(host);
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setDatabase(dbIndex);
if (StringUtils.isNotBlank(password)) {
jedisConnectionFactory.setPassword(password);
}
jedisConnectionFactory.setTimeout(TIMEOUT);
jedisConnectionFactory.setUsePool(USE_POOL);
jedisConnectionFactory.setPoolConfig(jedisPoolConfig());
jedisConnectionFactory.afterPropertiesSet();
RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
@ConditionalOnProperty(prefix = "redis", name = "cluster", havingValue = "true")
public RedisTemplate<?, ?> redisTemplateCluster() {
RedisNode clusterRedisNodes1 = new RedisNode(host, port);
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
Set<RedisNode> clusterNodes = new HashSet<>();
clusterNodes.add(clusterRedisNodes1);
redisClusterConfiguration.setClusterNodes(clusterNodes);
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration,
jedisPoolConfig());
jedisConnectionFactory.setDatabase(dbIndex);
if (StringUtils.isNotBlank(password)) {
jedisConnectionFactory.setPassword(password);
}
jedisConnectionFactory.afterPropertiesSet();
RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
标签:jedisConnectionFactory,SpringBoot,cluster,Bean,RedisTemplate,生效,new,redisTemplat
From: https://blog.51cto.com/u_14671216/6397682