vapor / redis

Vapor provider for RediStack
MIT License
459 stars 58 forks source link

Support for Multiple Redis instances #178

Closed danramteke closed 3 years ago

danramteke commented 3 years ago

Hello, excited for my second PR to this repo. <3 https://github.com/vapor/redis/pull/120

I discovered there wasn't support for multiple Redis instances, while upgrading my app from Vapor 3 to Vapor 4. This PR addresses this.

Usage

Assuming a redis1 ID has been defined,

extension RedisID {
    static var redis1: RedisID {
        RedisID(string: "redis1")
    }
}

The Redis configuration in configure.swift can look like this:

    app.redis.configuration = try RedisConfiguration(url: Environment.get("REDIS_URL")!)
    app.redis(.redis1).configuration = try RedisConfiguration(url: Environment.get("REDIS_URL_1")!)
    app.redis(.redis2).configuration = try RedisConfiguration(url: Environment.get("REDIS_URL_2")!)

and then the routes in routes.swift can look like this:

    app.get("redis") { req in
        req.redis.get("name").map { respValue in
            return respValue.string ?? "name not found in default Redis"
        }
    }

    app.get("redis1") { req in
        req.redis(.redis1).get("name").map { respValue in
            return respValue.string ?? "name not found in Redis 1"
        }
    }

Default Redis

The original app.redis.configuration = RedisConfiguation(...) syntax is still supported. It refers to the default Redis ID

The routes in routes.swift still look like

    app.get("redis") { req in
        req.redis.get("name").map { respValue in
            return respValue.string ?? "name not found in Redis"
        }
    }

Sample App

A sample app is available at https://github.com/danramteke/study-redis-multiple

Arch

I added a RedisStorage class that works similarly to the Databases class in Fluent. It holds on to the Redis configurations and connection pools. Just like what's on master, there is a connection pool per EventLoop. But now, a RedisID is also used.

The Application.Redis and Request.Redis structs still exist, and they get their Redis connection pool from app.redisStorage, which is an instance of RedisStorage

danramteke commented 3 years ago

Thanks, @gwynne ! I've applied your suggestions. I will address the others soon.

tanner0101 commented 3 years ago

These changes are now available in 4.1.0