koa-redis 正在参加 2021 年度 OSC 中国开源项目评选,请投票支持!
koa-redis 在 2021 年度 OSC 中国开源项目评选 中已获得 {{ projectVoteCount }} 票,请投票支持!
2021 年度 OSC 中国开源项目评选 正在火热进行中,快来投票支持你喜欢的开源项目!
2021 年度 OSC 中国开源项目评选 >>> 中场回顾
koa-redis 获得 2021 年度 OSC 中国开源项目评选「最佳人气项目」 !
授权协议 MIT License
开发语言 C#
操作系统 跨平台
软件类型 开源软件
所属分类 大数据数据存储
开源组织
地区 不详
投 递 者 首席测试
适用人群 未知
收录时间 2021-11-30

软件简介

koa-redis

build status Coveralls David deps David devDeps license code style styled with prettier made with lass

Redis storage for Koa session middleware/cache with Sentinel and Cluster support

NPM

v4.0.0+ now uses ioredis and has support for Sentinel and Cluster!

Table of Contents

Install

npm:

npm install koa-redis

yarn:

yarn add koa-redis

Usage

koa-redis works with koa-generic-session (a generic session middleware for koa).

For more examples, please see the examples folder of koa-generic-session.

Basic

const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');

const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({
  store: redisStore({
    // Options specified here
  })
}));

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-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');

const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({
  store: redisStore({
    // Options specified here
    // <https://github.com/luin/ioredis#sentinel>
    sentinels: [
      { host: 'localhost', port: 26379 },
      { host: 'localhost', port: 26380 }
      // ...
    ],
    name: 'mymaster'
  })
}));

// ...

Cluster

const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const koa = require('koa');

const app = koa();
app.keys = ['keys', 'keykeys'];
app.use(session({
  store: 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: {
        // ...
      }
    }
  })
}));

// ...

Options

  • all ioredis options - Useful things include url, host, port, and path to the server. Defaults to 127.0.0.1:6379
  • db (number) - will run client.select(db) after connection
  • client (object) - supply your own client, all other options are ignored unless duplicate is also supplied
  • duplicate (boolean) - When true, it will run client.duplicate() on the supplied client and 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 per ioredis Cluster options, if set to true, then a new Redis cluster will be instantiated with new Redis.Cluster(options.nodes, options.clusterOptions) (see Cluster docs for more info).
  • nodes (array) - Conditionally used for creating a Redis cluster instance when isRedisCluster option is true, this is the first argument passed to new Redis.Cluster and 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 when isRedisCluster option is true, this is the second argument passed to new Redis.Cluster and contains options, such as redisOptions (see Cluster docs for more info).
  • DEPRECATED: old options - auth_pass and pass have been replaced with password, and socket has been replaced with path, 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-generic-session uses that you can use manually. You will need to initialize differently than the example above:

const session = require('koa-generic-session');
const redisStore = require('koa-redis')({
  // Options specified here
});
const app = require('koa')();

app.keys = ['keys', 'keykeys'];
app.use(session({
  store: redisStore
}));

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().

session.end()

Alias to session.quit(). It is not safe to use the real end function, as it cuts off the queue.

session.status

String giving the connection status updated using client.status.

session.connected

Boolean giving the connection status updated using client.status after any of the events above is fired.

session.client

Direct access to the ioredis client object.

Benchmark

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

  1. Start a Redis server on localhost:6379. You can use redis-windows if you are on Windows or just want a quick VM-based server.
  2. Clone the repository and run npm i in it (Windows should work fine).
  3. If you want to see debug output, turn on the prompt's DEBUG flag.
  4. Run npm test to run the tests and generate coverage. To run the tests without generating coverage, run npm run-script test-only.

License

MIT © dead_horse

Contributors

Name Website
dead_horse
Nick Baugh http://niftylettuce.com/

展开阅读全文

代码

评论 (0)

加载中
更多评论
暂无内容
发表了博客
2018/07/30 09:42

koa源码阅读[1]-koa与koa-compose

接上次挖的坑,对koa2.x相关的源码进行分析 第一篇。 不得不说,koa是一个很轻量、很优雅的http框架,尤其是在2.x以后移除了co的引入,使其代码变得更为清晰。 express和koa同为一批人进行开发,与express相比,koa显得非常的迷你。 因为express是一个大而全的http框架,内置了类似router之类的中间件进行处理。 而在koa中,则将类似功能的中间件全部摘了出来,早期koa里边是内置了koa-compose的,而现在也是将其分了出来。 ko...

0
0
2018/04/25 15:06

Koa

一:koa-static的使用: // __dirname:当前文件路径 app.use(koaStatic('static',{ maxage:1000*5, //设置返回头的maxage字段 extensions:['.txt','.png'], // 当请求路径没有后缀时,默认使用此数据中匹配成功的第一个, index:'logo', //当省略请求路径文件时,默认的请求名称 default file name gzip:true,      //defaults to true, defer:false, hidden:false, setHeader:fals...

0
0
发表了博客
2018/08/09 15:46

koa源码阅读[2]-koa-router

koa源码阅读[2]-koa-router 第三篇,有关koa生态中比较重要的一个中间件:koa-router 第一篇:koa源码阅读-0 第二篇:koa源码阅读-1-koa与koa-compose koa-router是什么 首先,因为koa是一个管理中间件的平台,而注册一个中间件使用use来执行。 无论是什么请求,都会将所有的中间件执行一遍(如果没有中途结束的话) 所以,这就会让开发者很困扰,如果我们要做路由该怎么写逻辑? app.use(ctx => { switch (ctx.url) { ...

0
0
发表了博客
2020/08/14 07:57

koa脚手架

Koa脚手架 koa-generator是用于生成koa项目骨架的生成器 koa-generator提供的功能如下: 生成项目骨架,集成必要的中间件 约定目录结构 项目骨架结构描述 app.js为入口 bin/www为启动入口 支持静态服务器,即public目录 支持routes路由目录 支持views视图目录 默认将Pug作为模板引擎 安装Koa生成器 koa-generator支持Koa v1和Koa v2,安装后分别使用koa和koa2命令创建koa项目模板 创建Hello world koa2 helloworld 安装依赖模块...

0
0
发表了博客
2019/01/08 11:17

koa入门

创建koa2工程 首先初始化项目 npm init -y 项目名称 安装koa $ npm i koa 我们创建一个目录hello-koa并作为工程目录用VS Code打开。然后,我们创建app.js,输入以下代码: // 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示: const Koa = require('koa'); // 创建一个Koa对象表示web app本身: const app = new Koa(); // 对于任何请求,app将调用该异步函数处理请求: app.use(async...

0
0
没有更多内容
加载失败,请刷新页面
点击加载更多
加载中
下一页
暂无内容
0 评论
0 收藏
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部