node_redis中⽂⽂档及node_redis注释笔记(中⽂版)node_redis 中⽂⽂档及node_redis 注释笔记(中⽂版)
redis - a node.js redis client
这是node.js的⼀个完整且功能丰富的Redis客户端。它⽀持所有的Redis命令,并专注于⾼性能。
Install with:
npm install redis
Usage Example
var redis = require("redis"),
client = ateClient();
// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });
<("error", function (err) {
console.log("Error " + err);
});
client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
console.log(replies.length + " replies:");
replies.forEach(function (reply, i) {
console.log("    " + i + ": " + reply);
});
client.quit();
});
This will display:
mjr:~/work/node_redis (master)$ node example.js
Reply: OK
Reply: 0
Reply: 0
2 replies:
0: hashtest 1
1: hashtest 2
mjr:~/work/node_redis (master)$
请注意,该API完全是异步的。您需要使⽤⼀个回调,从服务器获取数据。⾃从2.6版本开始,API⽀持
在所有地⽅的选项、变量、事件等等使⽤驼峰和下划线命名规范。不过,建议使⽤Node.js默认的风格——驼峰式。
--------------------------------------------------
译者注:
关于异步我做了⼀个如下demo
var redis = require("redis"),
client = ateClient();
client.set("string key",true,()=>{
console.log(1)
});
console.log(2)
<("string key" ,(err,key)=>{
console.log(3)
});
console.log(4)
返回了
2
4
1
3
--------------------------------------------------
Promises
你也可以通过如下⽅式使⽤模块,将node_redis  promises化:
var redis = require('redis');
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
它将在所有node_redis函数后添加⼀个Async (例如 Async().then())
timeout of 5000ms exceeded// We expect a value 'foo': 'bar' to be present
// So instead of ('foo', cb); you have to write:
Async('foo').then(function(res) {
console.log(res); // => 'bar'
});
// Using multi with promises looks like:
return client.multi().get('foo').execAsync().then(function(res) {
console.log(res); // => 'bar'
});
--------------------------------------------------
译者注:
bluebird装饰后可以结合ES6的await/async使⽤
var redis = require("redis"),
bluebird = require("bluebird");
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
let client = ateClient();
(async  function () {
await client.setAsync("ip",1,"ex",10);
let ip = Async("ip");
await  client.setAsync("ip",++ip,"ex",10);
ip = Async("ip");
console.log(ip)
})();
--------------------------------------------------
Sending Commands
发送命令
每个Redis命令都作为client对象上的⼀个函数暴露出来。所有函数都采⽤⼀个args数组加上可选的callback函数,或者⼀个可变数量的的单独参数跟随⼀个可选的回调。例如:
client.hmset(["key", "test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
// Works the same as
client.hmset("key", ["test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
// Or
client.hmset("key", "test keys 1", "test val 1", "test keys 2", "test val 2", function (err, res) {});
Care should be taken with user input if arrays are possible (via body-parser, query string or other method), as single arguments could be unintentionally interpreted as multiple args.
(TODO)
注意,⽆论哪种形式,回调都是可选的:
client.set("some key", "some val");client.set(["some other key", "some val"]);
如果key不存在,将返回null。只有当特别声明,它才不会为空。
<("missingkey", function(err, reply) {    // reply is null when the key is missing
console.log(reply);
});
Redis命令列表,请参见
在返回结果中进⾏了最低限度的解析。命令中,integer 返回Javascript的Numbers, arrays 返回JavaScript Array. HGETALL返回hash keys 作为key的 Object  . 所有strings 将返回 string ,亦或者你特别设置返回类型为buffer类型。请注意:null, undefined 和Boolean 在返回中将强制转换为字符串。
--------------------------------------------------
译者注:
关于Boolean 在返回中将强制转换为字符串。我做了如下demo
var redis = require("redis"),
client = ateClient();
client.set("string key",true);
<("string key" ,(err,key)=>{
console.log(typeof key);
});
返回
string
--------------------------------------------------
Redis Commands
Redis命令
这个库跟命令⼀⼀映射。请参照Redis命令页获取完整的使⽤细节。
例如使⽤设置key值得⾃动失效时间
// this key will expire after 10 seconds
client.set('key', 'value!', 'EX', 10);
API
Connection and other Events
客户端将会发送⼀些关于连接到Redis服务器的状态的事件。
"ready"
client当连接建⽴后,将触发⼀次ready事件. 在ready事件之前发出的命令将被排队,ready事件触发后,队列中的命令依次执⾏。"connect"
⼀旦stream连接到服务器,client⽴即触发connect事件。
--------------------------------------------------
译者注:
关于“ready“,”connect”执⾏先后问题,设计了如下demo
var redis = require("redis"),
client = ateClient();
<("ready",()=>{
console.log("ready");
});
<("connect",()=>{
console.log("connect");
});
结果
connect
ready
--------------------------------------------------
"reconnecting"
在失去连接后,当尝试重新连接到Redis服务器,client将触发reconnecting事件。将被传递⼀个包含delay (in ms) 和attempt (the attempt #) 属性的对象。
"error"
当遇到连接到Redis服务器错误,或在node_redis中出现的任何其他错误时,client将触发error事件。如果你使⽤⼀个没有回调的命令,或者遇到返回异常时,错误将被触发。
因此,请将错误侦听器附加到node_redis上。
"end"
当已和Redis服务器建⽴的连接被关闭时,client将触发end事件。
"drain" (deprecated弃⽤)
当TCP连接到Redis server曾经被缓存,但现在是可写的(译者注:缓存池排⼲时)。这个事件将被⽤于流命令进⼊Redis,并适应背压。
当流被缓存client.should_buffer被设置为 true. 否则变量始终被设置为false。这样你能够决定何时降低发送速率,当触发drain事件时再恢复传输。
您也可以检查每个命令的返回值,因为它也将返回背压指⽰器(不建议使⽤)。如果返回false,则流必须缓冲。
--------------------------------------------------
译者注:
我写了⼀个drain测试demo
'use strict';
var redis = require('redis');
var client = ateClient({
return_buffers: true
});
client.auth("g7845120");
var fs = require('fs');
var filename = 'Funny-Cat-GIFs.jpg';
if (err) throw err;
console.log('Read ' + data.length + ' bytes from filesystem.');
client.set(filename, data, function () {
console.log("set end")
}); // set entire file
if(client.should_buffer){
client.stream.pause();
}
("drain",function () {
console.log("drain");
sume();
});
});
--------------------------------------------------
"warning"
当设置密码时,但不需要,并且使⽤了⼀个不赞成的选项/功能/类似。client将触发warning事件。
"idle" (deprecated弃⽤)
在没有正在等待响应的未完成命令时发出时,client将触发idle事件
如果你的node服务器和redis服务器运⾏在同⼀台机器上,那么默认设置的port和host或许是可⽤的,并且你不需要提供其他参
数。createClient()返回⼀个RedisClient对象。否则,createClient()需要接受这些参数:
提⽰:如果Redis服务器与客户端在同⼀台计算机上运⾏,请尽可能使⽤unix套接字来增加吞吐量。options object properties
Property Default Description host127.0.0.1IP address of the Redis server
port6379Port of the Redis server
path null The UNIX socket string of the Redis server
url null The URL of the Redis server. Format: [redis:]//[[user][:password@]][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]] (More info avaliable at ).
parser javascript Deprecated Use either the built-in JS parser  or the native  parser. Note node_redis < 2.6 uses hiredis as default if installed. This changed in v.2.6.0.
string_numbers null 设置为true,node_redis将返回String类型Redis的number值,以替代javascript的Nembers类型。当你需要处理⼀个⼤数字时有⽤(超过Number.MAX_SAFE_INTEGER === 2^53)。Hiredis⽆能为⼒,因此设置此选项true将导致⽆论parser选项的值如何,都会使⽤内置的JavaScript分析器。
return_buffers false如果设置为true,那么所有的返回值将以Buffers的形式替代Strings发送到回调函数.
detect_buffers false 如果设置为true,则返回值将以Buffers 发送到回调。此选项允许您在每个命令的基础上在Buffers和字符串之间切换,⽽return_buffers适⽤于客户端上的每个命令。注意:这与pubsub模式⽆法正常⼯作。⽤户必须总是返回字符串或Buffers。
socket_keepalive true如果设置为true,则在底层套接字上启⽤keep-alive功能。
no_ready_check false When a connection is established to the Redis server, the server might still be loading the database from disk. While loading, the server will not respond to any commands. To work around
this, node_redis has a "ready check" which sends the INFO command to the server. The response from the INFO command indicates whether the server is ready for more commands. When
ready, node_redis emits a ready event. Setting no_ready_check to true will inhibit this check.
enable_offline_queue true By default, if there is no active connection to the Redis server, commands are added to a queue and are executed once the connection has been established. Setting enable_offline_queue to false will disable this feature and the callback will be executed immediately with an error, or an error will be emitted if no callback is specified.
retry_max_delay null Deprecated Please use retry_strategy instead. By default, every time the client tries to connect and fails, the reconnection delay almost doubles. This delay normally grows infinitely, but
setting retry_max_delay limits it to the maximum value provided in milliseconds.
connect_timeout3600000Deprecated Please use retry_strategy instead. Setting connect_timeout limits the total time for the client to connect and reconnect. The value is provided in milliseconds and is counted from the moment a new client is created or from the time the connection is lost. The last r
etry is going to happen exactly at the timeout time. Default is to try connecting until the default system socket timeout has been exceeded and to try reconnecting until 1h has elapsed.
max_attempts0Deprecated Please use retry_strategy instead. By default, a client will try reconnecting until connected. Setting max_attempts limits total amount of connection attempts. Setting this to 1 will prevent any reconnect attempt.
retry_unfulfilled_commands false If set to true, all commands that were unfulfilled while the connection is lost will be retried after the connection has been reestablished. Use this with caution if you use state altering commands (e.g. incr). This is especially useful if you use blocking commands.
password null If set, client will run Redis auth command on connect. Alias auth_pass Note node_redis < 2.5 must use auth_pass
db null If set, client will run Redis select command on connect.
family IPv4You can force using IPv6 if you set the family to 'IPv6'. See Node.js  or modules on how to use the family type.
disable_resubscribing false If set to true, a client won't resubscribe after disconnecting.
rename_commands null Passing an object with renamed commands to use instead of the original functions. For example, if you renamed the command KEYS to "DO-NOT-USE" then the rename_commands object would be: { KEYS : "DO-NOT-USE" } . See the  for more info.
tls null An object containing options to pass to  to set up a TLS connection to Redis (if, for example, it is set up to be accessible via a tunnel).
prefix null A string used to prefix all used keys (e.g. namespace:test). Please be aware that the keys command will not be prefixed. The keys command has a "pattern" as argument and no key and it would be

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。