当前位置: 首页 > 软件库 > 大数据 > 数据存储 >

koa-redis

授权协议 MIT License
开发语言 C#
所属分类 大数据、 数据存储
软件类型 开源软件
地区 不详
投 递 者 佟翰林
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

koa-redis

build status

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

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/

  • 相对于MySQL和MongoDB,Koa操作Redis稍微顺利了点,没有遇到太多的问题。 看一段简单的demo: const redis = require('redis') const client = redis.createClient(6379, '127.0.0.1') client.on('error',(err)=>{ console.log(err); }) client.

  • 最近公司某个项目涉及到了视频直播的模块,看了网上许多案例都是基于rtmp或hls的方案进行直播的,考虑到日后chrome不再支持flash,于是试着结合MSE和node中间层进行直播流的推送和解析操作,其中就涉及到了node操作redis的环节。 一、配置ORM库 一般来说,无论服务端还是中间层,针对mysql和mongoDB这种数据库都会使用ORM进行操作,redis也一样,因此在开始使用red

  • 参考  https://www.npmjs.com/package/koa-session2 1 安装  npm install koa-session2 2 app.js const Koa = require('koa'); const app = new Koa(); const session = require('koa-session2'); const Store = require

  • 这两个都可以做消息队列,消息队列可以做什么? 消息队列 优点 解耦 ,将消息写到消息队列中,需要的系统来订阅 异步,加快速度 消峰,防止同时间大并发请求数据库,造成数据库连接异常,而通过消息队列的话,消费者可以根据数据库处理能力的并发量来拉去消息 缺点 系统可用性降低;系统复杂性增加 kafka可用性 kafka是分布式系统,通过zookeeper管理集群配置,选举leader,在consumer

  • package cn.iocoder.yudao.framework.redis.config; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.client.codec.StringCodec; import org.redisson.config.Config;

  • 列表(list) 列表( list)类型是用来存储多个有序的字符串,a、b、c、d、e五个元素从左到右组成了一个有序的列表,列表中的每个字符串称为元素(element),一个列表最多可以存储2的32次方-1个元素。在Redis 中,可以对列表两端插入( push)和弹出(pop),还可以获取指定范围的元素列表、获取指定索引下标的元素等。列表是一种比较灵活的数据结构,它可以充当栈和队列的角色,在实际

  • 一. 启动本机redis 1. 启动本机redis:在终端输入 redis-server 默认端口号为:6379 注意:这个终端不要关闭,关闭了之后redis也关了 2. 打开redis客户端测试一下:新开一个终端,输入 redis-cli 127.0.0.1:6379> set name '哈哈' OK 127.0.0.1:6379> get name "\xe5\x93\x88\xe5\x93

  • Node.js连接redis显示Client is Closed Node连接redis的代码如下: const redis = require('redis'); const client = redis.createClient(6379, 'localhost'); // const client = redis.createClient(); //获取当前db中所有的key // fu

 相关资料
  • Koa

    Koa art-template view render middleware. support all feature of art-template. Install npm install --save art-template npm install --save koa-art-template Example const Koa = require('koa'); const ren

  • koa

    koa是Express的下一代基于Node.js的web框架,目前有1.x和2.0两个版本。 历史 1. Express Express是第一代最流行的web框架,它对Node.js的http进行了封装,用起来如下: var express = require('express'); var app = express(); app.get('/', function (req, res) {

  • Koa

    Koa 是下一代的 Node.js 的 Web 框架。由 Express 团队设计。旨在提供一个更小型、更富有表现力、更可靠的 Web 应用和 API 的开发基础。 Koa可以通过生成器摆脱回调,极大地改进错误处理。Koa核心不绑定任何中间件,但提供了优雅的一组可以快速和愉悦地编写服务器应用的方法。 示例代码: var koa = require('koa');var app = koa();//

  • Koa - HelloWorld 以上便是全部了,我们重点来看示例,我们只注册一个中间件, Hello Worler Server: <?php $app = new Application(); // ... $app->υse(function(Context $ctx) { $ctx->status = 200; $ctx->body = "<h1>Hello Worl

  • koa-log4js A wrapper for log4js-node which support Koa logger middleware.Log message is forked from Express (Connect) logger file. Note This branch is use to Koa v2.x.To use Koa v0.x & v1.x, please ch

  • koa-rudy 环境 node -v >=6.9.0pm2 启动 npm install npm run dev 开发环境 npm run dev || test || prod 接口测试 npm run mocha 推荐开发工具 vscode 实现 支持 async/await MVC架构(middleware-view-controller) RESTful a