Coder Social home page Coder Social logo

egg-redis's Introduction

egg-redis

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Redis client(support redis portocal) based on ioredis for egg framework

Install

$ npm i egg-redis --save

redis Plugin for egg, support egg application access to redis.

This plugin based on ioredis, if you want to know specific usage, you should refer to the document of ioredis.

Configuration

Change ${app_root}/config/plugin.js to enable redis plugin:

exports.redis = {
  enable: true,
  package: 'egg-redis',
};

Configure redis information in ${app_root}/config/config.default.js:

Single Client

config.redis = {
  client: {
    port: 6379,          // Redis port
    host: '127.0.0.1',   // Redis host
    password: 'auth',
    db: 0,
  },
}

Multi Clients

config.redis = {
  clients: {
    foo: {                 // instanceName. See below
      port: 6379,          // Redis port
      host: '127.0.0.1',   // Redis host
      password: 'auth',
      db: 0,
    },
    bar: {
      port: 6379,
      host: '127.0.0.1',
      password: 'auth',
      db: 1,
    },
  }
}

Sentinel

config.redis = {
  client: {
    sentinels: [{          // Sentinel instances
      port: 26379,         // Sentinel port
      host: '127.0.0.1',   // Sentinel host
    }],
    name: 'mymaster',      // Master name
    password: 'auth',
    db: 0
  },
}

No password

Redis support no authentication access, but we are highly recommand you to use redis requirepass in redis.conf.

$vim /etc/redis/redis.conf

requirepass xxxxxxxxxx  // xxxxxxxxxx is your password

Because it may be cause security risk, refer:

If you want to access redis with no password, use password: null.

See ioredis API Documentation for all available options.

Customize ioredis version

egg-redis using ioredis@4 now, if you want to use other version of ioredis, you can pass the instance by config.redis.Redis:

// config/config.default.js
config.redis = {
  Redis: require('ioredis'), // customize ioredis version, only set when you needed
  client: {
    port: 6379,          // Redis port
    host: '127.0.0.1',   // Redis host
    password: 'auth',
    db: 0,
  },
}

weakDependent

config.redis = {
  client: {
    port: 6379,          // Redis port
    host: '127.0.0.1',   // Redis host
    password: 'auth',
    db: 0,
    weakDependent: true, // this redis instance won't block app start
  },
}

Usage

In controller, you can use app.redis to get the redis instance, check ioredis to see how to use.

// app/controller/home.js

module.exports = app => {
  return class HomeController extends app.Controller {
    async index() {
      const { ctx, app } = this;
      // set
      await app.redis.set('foo', 'bar');
      // get
      ctx.body = await app.redis.get('foo');
    }
  };
};

Multi Clients

If your Configure with multi clients, you can use app.redis.get(instanceName) to get the specific redis instance and use it like above.

// app/controller/home.js

module.exports = app => {
  return class HomeController extends app.Controller {
    async index() {
      const { ctx, app } = this;
      // set
      await app.redis.get('instance1').set('foo', 'bar');
      // get
      ctx.body = await app.redis.get('instance1').get('foo');
    }
  };
};

Clients Depend on Redis Cluster

Before you start to use Redis Cluster, please checkout the document first, especially confirm cluster-enabled yes in Redis Cluster configuration file.

In controller, you also can use app.redis to get the redis instance based on Redis Cluster.

// app/config/config.default.js

exports.redis = {
   client: {
     cluster: true,
     nodes: [{
       host: '127.0.0.1',
       port: '6379',
       family: 'user',
       password: 'password',
       db: 'db',
     }, {
       host: '127.0.0.1',
       port: '6380',
       family: 'user',
       password: 'password',
       db: 'db',
     }]
   },
};

// app/controller/home.js

module.exports = app => {
  return class HomeController extends app.Controller {
    async index() {
      const { ctx, app } = this;
      // set
      await app.redis.set('foo', 'bar');
      // get
      ctx.body = await app.redis.get('foo');
    }
  };
};

Questions & Suggestions

Please open an issue here.

License

MIT

egg-redis's People

Contributors

atian25 avatar brickyang avatar dead-horse avatar fengmk2 avatar hhhluke avatar jollysun avatar jtyjty99999 avatar killagu avatar kylezhang avatar marshalys avatar qingdengyue avatar qiqizjl avatar whxaxes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

egg-redis's Issues

多实例有问题

app.redis.get('bar')获取不到实例,我已经在配置里写了client里面有两个对象实例

nodejs.ReplyError: NOAUTH Authentication required.

在请求接口 /test的时候,报错。redis的host、port以及password都是正确的,不知道是哪里出现了问题
egg-redis版本:^2.5.0
egg版本:^3

报错信息

2023-06-16 16:59:34,096 ERROR 60949 nodejs.ReplyError: NOAUTH Authentication required.
   at parseError (/app/node_modules/redis-parser/lib/parser.js:179:12)
   at parseType (/app/node_modules/redis-parser/lib/parser.js:302:14)
command: {"name":"info","args":[]}
pid: 60949
hostname: sz-user.local

router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/test', controller.home.test);
  router.get('/', controller.home.index);
};

controller/home.js

'use strict';

const { Controller } = require('egg');

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async test() {
    const { ctx, app } = this;
    console.log('test start')
    // set
    await app.redis.set('foo', 'bar');
    // get
    ctx.body = await app.redis.get('foo');
  }
}

module.exports = HomeController;

plugin.js

'use strict';

/** @type Egg.EggPlugin */
module.exports = {
  // had enabled by egg
  // static: {
  //   enable: true,
  // }
  redis: {
    enable: true,
    package: 'egg-redis'
  }
};

config.default.js

/* eslint valid-jsdoc: "off" */

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {};


  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1686821889236_483';

  // add your middleware config here
  config.middleware = [];

  config.redis ={
    // Redis: require('ioredis'),
    client: {
      cluster: true,
      nodes: [{
        host: '*.*.*.*.',
        port: '*',
        password: '*******',
        db: 0,
        // autoResubscribe: true
      }]
    },
  }

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };
  

  return {
    ...config,
    ...userConfig
  };
};

egg-redis Clients Depend on Redis Cluster ERROR

"egg-redis": "^2.4.0",
"egg": "^2.5.0"

本地搭建的的redis集群测试(集群状态正常)
image

用127.0.0.1是正常连接的,切换成内外ip就无法连接了

配置
image

报错信息
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.