6

I'm using spring-data-redis, spring-session and Spring Boot to connect to my Redis instance. However I would like spring-data-redis to connect not to DB 0 (which is default) but to another local database (say DB 1). This is where I'd like the sessions to be stored. Is this possible with spring-data-redis?

Johan
  • 37,479
  • 32
  • 149
  • 237

1 Answers1

11

The ConnectionFactory used by RedisTemplate offers configuration options for setting a default DB. Depending on the Redis driver in use both JedisConnectionFactory as well as LettuceConnectionFactory offer void setDatabase(int index).

Using Spring Boot RedisProperties allows to set the default DB via setDatabase or by providing spring.redis.database.

Christoph Strobl
  • 6,491
  • 25
  • 33
  • Christoph Strobl is it ok if I inject JedisConnectionFactory in my bean and change database in runtime, cause I need to have two different databases?? – idmitriev Mar 10 '17 at 11:36
  • I would not recommend doing this but rather use the `select` method offered via `RedisConnectionCommands` on the dedicated connection you're working with. – Christoph Strobl Mar 10 '17 at 11:44
  • Thank you, I need to call to two different databases in one application. – idmitriev Mar 10 '17 at 11:49
  • Christoph Strobl how can I get 'RedisConnectionCommands' ?? I just can get connection from connectionFactory.getConnection().select(index), but it will take a new connection. – idmitriev Mar 10 '17 at 12:00
  • and I am using JedisConnectionFactory, is it true that the JedisConnectionFactory only supports connecting to one Redis database at a time?? – idmitriev Mar 10 '17 at 12:12
  • Using `Jedis` the connection factory will give you a connection from the pool. When using the `ConnectionFactory` along with the template switching `db` on factory level might result in strange behavior especially in multithreaded environments, assuming the factory is registered as a spring bean in context. Therefore it's safer to select the `db` after retrieving the connection from the factory. One way would be to set up multiple dedicated factories and templates - one for each db. – Christoph Strobl Mar 14 '17 at 07:15
  • 2
    Agree, I've decided to do in on connection level, I use redisTemplate.execute( con -> {con.select(dbIndex); // do stuff } – idmitriev Mar 14 '17 at 09:57