您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關springboot中怎么配置創建多個redis,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
以下是配置的定義規范:
spring: redis: timeout: 1000 lettuce: pool: maxActive: 2500 max-wait: 6000 max-idle: 500 min-idle: 100 sentinels: temp1: master: a nodes: ip1:10201,ip2:10202 password: temp2: master: b nodes: ip3:10201,ip4:10202 password: primary: true //是否主要的bean
配置中其他的redis配置還是遵循springboot官方的,但另外擴展了一個sentinels屬性,這個屬性填充多個redis 配置信息,由于我們項目主要使用哨兵模式,故這里使用sentinel方式實現。
其次配置類根據上面的配置信息可以定義了:
@ConfigurationProperties(prefix = "spring.redis.sentinels") public class RedisExtProperties extends HashMap<String, ExtSentinel>{ private static final long serialVersionUID = 856175258267105532L; public static class ExtSentinel extends Sentinel { private String password; private boolean primary; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isPrimary() { return primary; } public void setPrimary(boolean primary) { this.primary = primary; } } }
以上是獲取配置信息的配置類了,接下來要通過某些手段去生成StringRedisTemplate的bean了,由于有多個bean,而且bean的名稱要自己通過配置文件中定義的,通過注解@Bean或者xml等方式貌似都無法達到目的,這里就利用BeanDefinitionRegistryPostProcessor接口去實現,該接口怎么使用可以去查看spring的一些文檔或者網上搜索都可以找到,這里不在贅述。
這個接口有兩個方法postProcessBeanFactory、postProcessBeanDefinitionRegistry,這兩個方法都可以實現動態注冊bean,大家也可以去網上搜索,但是呢,這里卻不能通過這兩個方法去實現動態注冊StringRedisTemplate的bean,因為在初始化BeanDefinitionRegistryPostProcessor這個接口的實現時,還并沒有完全加載springboot的相關配置,導致在這兩個方法里或者通過注解@Autowired都無法把RedisExtProperties注入進來,即便注入進來,也是沒有把相關配置信息初始化進去的,這把就坑了,后面想了半天直接通過AutowiredAnnotationBeanPostProcessor這個實現,重寫它的postProcessProperties方法去觸發動態注冊bean。
@Component public class RedisCustomFactory extends AutowiredAnnotationBeanPostProcessor implements BeanDefinitionRegistryPostProcessor { private final Logger logger = LoggerFactory.getLogger(getClass()); BeanDefinitionRegistry registry; ConfigurableListableBeanFactory factory; AtomicBoolean open = new AtomicBoolean(false); @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { if (!open.get()) { processFields(bean, bean.getClass().getDeclaredFields()); } return super.postProcessProperties(pvs, bean, beanName); } private void processFields(Object bean, Field[] declaredFields) { for (Field field : declaredFields) { if (!open.get() && field.getType().isAssignableFrom(RedisOperations.class)) { register(factory.getBean(RedisProperties.class), factory.getBean(RedisExtProperties.class), factory.getBeanProvider(LettuceClientConfigurationBuilderCustomizer.class)); open.compareAndSet(false, true); } } } private LettuceClientConfigurationBuilder createBuilder(Pool pool) { if (pool == null) { return LettuceClientConfiguration.builder(); } return new PoolBuilderFactory().createBuilder(pool); } // private void customize(LettuceClientConfiguration.LettuceClientConfigurationBuilder builder, // ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers) { // builderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); // } private LettuceClientConfigurationBuilder applyProperties( LettuceClientConfiguration.LettuceClientConfigurationBuilder builder, RedisProperties properties) { if (properties.isSsl()) { builder.useSsl(); } if (properties.getTimeout() != null) { builder.commandTimeout(properties.getTimeout()); } if (properties.getLettuce() != null) { RedisProperties.Lettuce lettuce = properties.getLettuce(); if (lettuce.getShutdownTimeout() != null && !lettuce.getShutdownTimeout().isZero()) { builder.shutdownTimeout(properties.getLettuce().getShutdownTimeout()); } } return builder; } private LettuceClientConfiguration getLettuceClientConfiguration(ClientResources clientResources, Pool pool, RedisProperties properties, ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers) { LettuceClientConfigurationBuilder builder = createBuilder(pool); applyProperties(builder, properties); builder.clientResources(clientResources); // customize(builder, builderCustomizers); return builder.build(); } private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) { List<RedisNode> nodes = new ArrayList<>(); for (String node : sentinel.getNodes()) { try { String[] parts = StringUtils.split(node, ":"); Assert.state(parts.length == 2, "Must be defined as 'host:port'"); nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1]))); } catch (RuntimeException ex) { throw new IllegalStateException("Invalid redis sentinel " + "property '" + node + "'", ex); } } return nodes; } protected RedisSentinelConfiguration getSentinelConfig(ExtSentinel sentinelProperties, RedisProperties properties) { if (sentinelProperties != null) { RedisSentinelConfiguration config = new RedisSentinelConfiguration(); config.master(sentinelProperties.getMaster()); config.setSentinels(createSentinels(sentinelProperties)); if (sentinelProperties.getPassword() != null) { config.setPassword(RedisPassword.of(sentinelProperties.getPassword())); } config.setDatabase(properties.getDatabase()); return config; } return null; } private LettuceConnectionFactory createLettuceConnectionFactory(LettuceClientConfiguration clientConfiguration, RedisSentinelConfiguration redisSentinelConfiguration, RedisProperties properties) { return new LettuceConnectionFactory(redisSentinelConfiguration, clientConfiguration); } private LettuceConnectionFactory redisConnectionFactory(ClientResources clientResources, RedisSentinelConfiguration redisSentinelConfiguration, RedisProperties properties, ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers) throws UnknownHostException { LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(clientResources, properties.getLettuce().getPool(), properties, null); return createLettuceConnectionFactory(clientConfig, redisSentinelConfiguration, properties); } public synchronized void register(RedisProperties properties, RedisExtProperties extProperties, ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers) throws BeansException { if (extProperties == null) { return; } extProperties.forEach((name, sentinel) -> { try { if (!factory.containsBeanDefinition(name + "RedisTemplate")) { logger.info("{} -----> {}", name, sentinel.isPrimary()); DefaultClientResources res = DefaultClientResources.create(); BeanDefinitionBuilder builder0 = BeanDefinitionBuilder .genericBeanDefinition(DefaultClientResources.class, () -> res); BeanDefinition beanDefinition0 = builder0.getRawBeanDefinition(); beanDefinition0.setPrimary(sentinel.isPrimary()); beanDefinition0.setDestroyMethodName("shutdown"); registry.registerBeanDefinition(name + "DefaultClientResources", beanDefinition0); LettuceConnectionFactory ref = redisConnectionFactory(res, getSentinelConfig(sentinel, properties), properties, builderCustomizers); BeanDefinitionBuilder builder1 = BeanDefinitionBuilder .genericBeanDefinition(RedisConnectionFactory.class, () -> ref); BeanDefinition beanDefinition1 = builder1.getRawBeanDefinition(); beanDefinition1.setPrimary(sentinel.isPrimary()); registry.registerBeanDefinition(name + "RedisConnectionFactory", beanDefinition1); BeanDefinitionBuilder builder2 = BeanDefinitionBuilder .genericBeanDefinition(StringRedisTemplate.class, () -> { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(ref); return template; }); BeanDefinition beanDefinition2 = builder2.getRawBeanDefinition(); beanDefinition2.setPrimary(sentinel.isPrimary()); registry.registerBeanDefinition(name + "RedisTemplate", beanDefinition2); } } catch (Exception ex) { logger.error("register redisProperties error", ex); } }); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException { this.factory = factory; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { this.registry = registry; } @Override public int getOrder() { return super.getOrder() - 1; } }
public class PoolBuilderFactory { public LettuceClientConfigurationBuilder createBuilder(Pool properties) { return LettucePoolingClientConfiguration.builder().poolConfig(getPoolConfig(properties)); } private GenericObjectPoolConfig<?> getPoolConfig(Pool properties) { GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>(); config.setMaxTotal(properties.getMaxActive()); config.setMaxIdle(properties.getMaxIdle()); config.setMinIdle(properties.getMinIdle()); if (properties.getTimeBetweenEvictionRuns() != null) { config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns().toMillis()); } if (properties.getMaxWait() != null) { config.setMaxWaitMillis(properties.getMaxWait().toMillis()); } return config; } }
根據代碼的細節,可以看到sentinels其實是一個map,會把sentinels的key和RedisTemplate拼接成bean的名字,所以在使用的過程中,如果有primary配置的直接使用@Autowired就可以直接注入了,其他的則@Qualifier+@Autowired既可以注入了。
@Autowired private StringRedisTemplate stringRedisTemplate;//對應的master 為b的 @Autowired @Qualifier("temp1RedisTemplate") private StringRedisTemplate microblogRedisTemplate;//對應的master 為a的
關于springboot中怎么配置創建多個redis就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。