Dynamically creating RedisTemplate for connecting with different Redis server

2k views Asked by At

My application is built on spring boot and is backed by Redis datastore. Currently I have a connection only to a single redis server and the properties of that server ( host / port ) is defined in bootstrap.yml.

I want to support multi-tenancy by using a separate Redis server for each customer. In order to do this I need to dynamically connect with various different redis server at runtime. Is it possible with RedisTemplate and JedisConnecitonFactory ?

1

There are 1 answers

1
mp911de On

In short

No need for multiple RedisTemplate instances; implement a routing RedisConnectionFactory.

Explanation

RedisTemplate uses an underlying RedisConnectionFactory to obtain connections. To route Redis operations to different connections, just implement a routing variant of RedisConnectionFactory. RedisTemplate asks the associated RedisConnectionFactory for each operation to provide a RedisConnection.

You need to pay attention when using transactions. Transactional use binds the Redis connection to the calling Thread and RedisTemplate works effectively on the same connection until the transaction is finished.

Take a look at AbstractRoutingDataSource to get an idea how data source routing is supported for JDBC connections. A routing RedisConnectionFactory could follow the same pattern.