koa-redis-snowman v1.0.3
koa-redis
Redis storage for Koa session middleware/cache with Sentinel and Cluster support
A fork of koa-redis, rewritten in typescript and with better support for koa-session
Table of Contents
Install
npm:
npm install koa-redisyarn:
yarn add koa-redisUsage
koa-redis-snowman works with koa-session (a basic session middleware for koa).
Basic
const Session = require('koa-session-snowman');
const RedisStore = require('koa-redis');
const koa = require('koa');
const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(new Session({
store: new RedisStore({
// Options specified here
})
}, app));
app.use(function *() {
switch (this.path) {
case '/get':
get.call(this);
break;
case '/remove':
remove.call(this);
break;
case '/regenerate':
yield regenerate.call(this);
break;
}
});
function get() {
const session = this.session;
session.count = session.count || 0;
session.count++;
this.body = session.count;
}
function remove() {
this.session = null;
this.body = 0;
}
function *regenerate() {
get.call(this);
yield this.regenerateSession();
get.call(this);
}
app.listen(8080);Sentinel
const Session = require('koa-session');
const RedisStore = require('koa-redis');
const koa = require('koa');
const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(new Session({
store: new RedisStore({
// Options specified here
// <https://github.com/luin/ioredis#sentinel>
sentinels: [
{ host: 'localhost', port: 26379 },
{ host: 'localhost', port: 26380 }
// ...
],
name: 'mymaster'
})
}, app));
// ...Cluster
const Session = require('koa-session');
const RedisStore = require('koa-redis');
const koa = require('koa');
const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(new Session({
store: new RedisStore({
// Options specified here
// <https://github.com/luin/ioredis#cluster>
isRedisCluster: true,
nodes: [
{
port: 6380,
host: '127.0.0.1'
},
{
port: 6381,
host: '127.0.0.1'
}
// ...
],
// <https://github.com/luin/ioredis/blob/master/API.md#new-clusterstartupnodes-options>
clusterOptions: {
// ...
redisOptions: {
// ...
}
}
})
}, app));
// ...Options
- all
ioredisoptions - Useful things includeurl,host,port, andpathto the server. Defaults to127.0.0.1:6379 db(number) - will runclient.select(db)after connectionclient(object) - supply your own client, all other options are ignored unlessduplicateis also suppliedduplicate(boolean) - When true, it will runclient.duplicate()on the suppliedclientand use all other options supplied. This is useful if you want to select a different DB for sessions but also want to base from the same client object.serialize- Used to serialize the data that is saved into the store.unserialize- Used to unserialize the data that is fetched from the store.isRedisCluster(boolean) - Used for creating a Redis cluster instance perioredisCluster options, if set totrue, then a new Redis cluster will be instantiated withnew Redis.Cluster(options.nodes, options.clusterOptions)(see Cluster docs for more info).nodes(array) - Conditionally used for creating a Redis cluster instance whenisRedisClusteroption istrue, this is the first argument passed tonew Redis.Clusterand contains a list of all the nodes of the cluster ou want to connect to (see Cluster docs for more info).clusterOptions(object) - Conditionally used for created a Redi cluster instance whenisRedisClusteroption istrue, this is the second argument passed tonew Redis.Clusterand contains options, such asredisOptions(see Cluster docs for more info).- DEPRECATED: old options -
auth_passandpasshave been replaced withpassword, andsockethas been replaced withpath, however all of these options are backwards compatible.
Events
See the ioredis docs for more info.
Note that as of v4.0.0 the disconnect and warning events are removed as ioredis does not support them. The disconnect event is deprecated, although it is still emitted when end events are emitted.
API
These are some the functions that koa-session uses that you can use manually. You will need to initialize differently than the example above:
const Session = require('koa-session');
const RedisStore = require('koa-redis')({
// Options specified here
});
const app = require('koa')();
app.keys = ['keys', 'keykeys'];
app.use(new Session({
store: new RedisStore
}, app));module(options)
Initialize the Redis connection with the optionally provided options (see above). The variable session below references this.
session.get(sid)
Generator that gets a session by ID. Returns parsed JSON is exists, null if it does not exist, and nothing upon error.
session.set(sid, sess, ttl)
Generator that sets a JSON session by ID with an optional time-to-live (ttl) in milliseconds. Yields ioredis's client.set() or client.setex().
session.destroy(sid)
Generator that destroys a session (removes it from Redis) by ID. Tields ioredis's client.del().
session.quit()
Generator that stops a Redis session after everything in the queue has completed. Yields ioredis's client.quit().
Benchmark
Note: these are from the generator based version, should retry with new async version.
| Server | Transaction rate | Response time |
|---|---|---|
| connect without session | 6763.56 trans/sec | 0.01 secs |
| koa without session | 5684.75 trans/sec | 0.01 secs |
| connect with session | 2759.70 trans/sec | 0.02 secs |
| koa with session | 2355.38 trans/sec | 0.02 secs |
Detailed benchmark report here
Testing
- Start a Redis server on
localhost:6379. You can useredis-windowsif you are on Windows or just want a quick VM-based server. - Clone the repository and run
npm iin it (Windows should work fine). - If you want to see debug output, turn on the prompt's
DEBUGflag. - Run
npm testto run the tests and generate coverage. To run the tests without generating coverage, runnpm run-script test-only.
License
MIT © dead_horse
Contributors
| Name | Website |
|---|---|
| dead_horse | |
| Nick Baugh | http://niftylettuce.com/ |
| ohjames |