Java Spring Redis - 从 application.properties 文件中读取配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34201135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:24:21  来源:igfitidea点击:

Spring Redis - Read configuration from application.properties file

javaspringconfigurationredis

提问by Shrikant Havale

I have Spring Redis working using spring-data-rediswith all default configuration likes localhostdefault portand so on.

我让 Spring Redis 使用spring-data-redis所有默认配置,如localhost默认port等。

Now I am trying to make the same configuration by configuring it in application.propertiesfile. But I cannot figure out how should I create beans exactly that my property values are read.

现在我试图通过在application.properties文件中配置它来进行相同的配置。但是我无法弄清楚我应该如何准确创建读取我的属性值的 bean。

Redis Configuration File

Redis 配置文件

@EnableRedisHttpSession
@Configuration
public class SpringSessionRedisConfiguration {

@Bean
JedisConnectionFactory connectionFactory() {
    return new JedisConnectionFactory();
}

@Autowired
@Bean
RedisCacheManager redisCacheManager(final StringRedisTemplate stringRedisTemplate) {
    return new RedisCacheManager(stringRedisTemplate);
}

@Autowired
@Bean
StringRedisTemplate template(final RedisConnectionFactory connectionFactory) {
    return new StringRedisTemplate(connectionFactory);
}
}

Standard Parameters in application.properties

application.properties 中的标准参数

spring.redis.sentinel.master=themaster

spring.redis.sentinel.nodes=192.168.188.231:26379

spring.redis.password=12345

spring.redis.sentinel.master=themaster

spring.redis.sentinel.nodes=192.168.188.231:26379

spring.redis.password=12345

What I tried,

我试过的,

  1. I can possibly use @PropertySourceand then inject @Valueand get the values. But I don't want to do that as those properties are not defined by me but are from Spring.
  2. In this documentation Spring Redis Documentation, it only says that it can be configured using properties but doesn't show concrete example.
  3. I also went through Spring Data Redis API classes, and found that RedisPropertiesshould help me, but still cannot figure out how exactly to tell Spring to read from properties file.
  1. 我可以使用@PropertySource然后注入@Value并获取值。但我不想这样做,因为这些属性不是由我定义的,而是来自 Spring。
  2. 在这个文档Spring Redis Documentation 中,它只说它可以使用属性进行配置,但没有显示具体示例。
  3. 我还浏览了 Spring Data Redis API 类,发现这RedisProperties应该对我有帮助,但仍然无法弄清楚如何告诉 Spring 从属性文件中读取。

采纳答案by misterion

You can use @PropertySourceto read options from application.properties or other property file you want. Please look PropertySource usage exampleand working example of usage spring-redis-cache. Or look at this small sample:

您可以使用@PropertySource从 application.properties 或其他您想要的属性文件中读取选项。请查看PropertySource 使用示例使用 spring-redis-cache 的工作示例。或者看看这个小样本:

@Configuration
@PropertySource("application.properties")
public class SpringSessionRedisConfiguration {

    @Value("${redis.hostname}")
    private String redisHostName;

    @Value("${redis.port}")
    private int redisPort;

    @Bean
    public static PropertySourcesPlaceholderConfigurer    propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisHostName);
        factory.setPort(redisPort);
        factory.setUsePool(true);
        return factory;
    }

    @Bean
    RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }

    @Bean
    RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        return redisCacheManager;
    }
}

In present time (december 2015) the spring.redis.sentineloptions in application.propertieshas limited support of RedisSentinelConfiguration:

目前(2015 年 12 月)中的spring.redis.sentinel选项application.properties有限支持RedisSentinelConfiguration

Please note that currently only Jedisand lettuce Lettucesupport Redis Sentinel.

请注意,目前只有Jedis和 lettuce Lettuce支持 Redis Sentinel。

You may read more about this in official documentation.

您可以在官方文档中阅读更多相关信息。

回答by Wheelchair Geek

I found this within the spring boot doc section 24 paragraph 7

我在 spring boot doc section 24 第 7 段中找到了这个

@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

    private String username;

    private InetAddress remoteAddress;

    // ... getters and setters

} 

Properties can then be modified via connection.property

然后可以通过 connection.property 修改属性

Reference link: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

参考链接:https: //docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties

回答by Wheelchair Geek

Upon looking deeper I found this, could it be what you are looking for?

深入研究后,我发现了这个,这可能是您要找的吗?

# REDIS (RedisProperties)
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0 # Connection timeout in milliseconds. 

Refernce:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.htmlSearchterm Redis

参考:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html Searchterm Redis

From what I can see the values already exist and are defined as

从我可以看到的值已经存在并被定义为

spring.redis.host=localhost # Redis server host.
spring.redis.port=6379 # Redis server port.

if you want to create your own properties you can look at my previous post in this thread.

如果您想创建自己的属性,可以查看我在此线程中的上一篇文章。

回答by Kylo Zhang

You can use the ResourcePropertySource to generate a PropertySource object.

您可以使用 ResourcePropertySource 生成 PropertySource 对象。

PropertySource propertySource = new ResourcePropertySource("path/to/your/application.properties");

Then pass it to the constructor of the RedisSentinelConfiguration.

然后将其传递给 RedisSentinelConfiguration 的构造函数。

回答by Andy

@Autowired
private JedisConnectionFactory connectionFactory;

@Bean
JedisConnectionFactory connectionFactory() {
    return connectionFactory
}

回答by Kelevra

Here is an elegant solution to solve your issue :

这是一个优雅的解决方案来解决您的问题:

@Configuration
@PropertySource(name="application", value="classpath:application.properties")
public class SpringSessionRedisConfiguration {

    @Resource
    ConfigurableEnvironment environment;

    @Bean
    public PropertiesPropertySource propertySource() {
        return (PropertiesPropertySource) environment.getPropertySources().get("application");
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory(sentinelConfiguration(), poolConfiguration());
    }

    @Bean
    public RedisSentinelConfiguration sentinelConfiguration() {
        return new RedisSentinelConfiguration(propertySource());
    }

    @Bean
    public JedisPoolConfig poolConfiguration() {
        JedisPoolConfiguration config = new JedisPoolConfiguration();
        // add your customized configuration if needed
        return config;
    }

    @Bean
    RedisTemplate<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }

    @Bean
    RedisCacheManager cacheManager() {
        return new RedisCacheManager(redisTemplate());
    }

}

so, to resume :

所以,要继续:

  • add a specific name for the @PropertySource
  • inject a ConfigurableEnvironment instead of Environment
  • get the PropertiesPropertySource in your ConfigurableEnvironment using the name you mentioned on your @PropertySource
  • Use this PropertySource object to construct your RedisSentinelConfiguration object
  • Don't forget to add 'spring.redis.sentinel.master' and 'spring.redis.sentinel.nodes' properties in you property file
  • 为 @PropertySource 添加特定名称
  • 注入 ConfigurableEnvironment 而不是 Environment
  • 使用您在@PropertySource 中提到的名称在您的 ConfigurableEnvironment 中获取 PropertiesPropertySource
  • 使用这个 PropertySource 对象来构造你的 RedisSentinelConfiguration 对象
  • 不要忘记在您的属性文件中添加“spring.redis.sentinel.master”和“spring.redis.sentinel.nodes”属性

Tested in my workspace, Regards

在我的工作区中测试,问候

回答by tarun goel

Use @DirtiesContext(classMode = classmode.AFTER_CLASS)at each test class. This will surely work for you.

使用@DirtiesContext(classMode = classmode.AFTER_CLASS)在每个测试类。这肯定对你有用。

回答by user2846650

This works for me :

这对我有用:

@Configuration
@EnableRedisRepositories
public class RedisConfig {

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisProperties properties = redisProperties();
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(properties.getHost());
        configuration.setPort(properties.getPort());

        return new JedisConnectionFactory(configuration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
        return template;
    }

    @Bean
    @Primary
    public RedisProperties redisProperties() {
        return new RedisProperties();
    }

}

and properties file :

和属性文件:

spring.redis.host=localhost
spring.redis.port=6379