要使用redis-sentinel-client,必须先安装redis-sentinel-client模块
npm install redis-sentinel-client
我们会将公用的配置信息放入配置文件,config.js内容如下:
exports.redisSentinel = { host: '192.168.199.55', port: 26379, opts: { auth_pass: '' } };
以下为封装的redis操作模块redis.js
var config = require('../../config'); var redisSentinel = require('redis-sentinel-client'); var client = redisSentinel.createClient(config.redisSentinel.port, config.redisSentinel.host, config.redisSentinel.opts); client.auth(config.redis.opts.auth_pass, function() { console.log('通过认证'); }); client.on('ready', function(res){ console.log('ready'); }); exports.get = function(key, callback) { client.on('connect', function(res) { client.get(key, callback); }); }; exports.set = function(key, value, callback) { client.on('connect', function(res) { client.set(key, value, callback); }); }; //设置值,同时设定过期时间 exports.setEx = function(key, value, timeout, callback) { client.on('connect', function(res) { client.set(key, value, callback); client.expire(key, timeout); }); }; function test(){ exports.setEx('nodejs', 'test', 30, function(err, res) { if(err) { throw err; } console.log('设置值'+res); }); exports.get('nodejs', function(err, res) { if(err) { throw err; } console.log('取值'+res); }); }; test();
感谢您的阅读,希望对您有帮助,本文版权归 #惊讶# 所有