Nodejs Learning Notes (ix)---Getting Started with redis interaction (Mranney/node_redis)

Source: Internet
Author: User
Tags redis server

Directory
    • Introduction and Installation
      • About Redis
      • Redis Installation
      • Redis Run
      • Node_redis Installation
    • Connect to Redis server Redis.createclient ()
    • Certified Client.auth (password, callback)
    • Single-valued set and get
      • Client.set (Key,value,[callback])
      • Client.get (Key,[callback])
      • Client.set ([Key,value],callback)
    • Multi-valued get and set
      • Client.hmset (Hash,obj,[callback])
      • Client.hmset (Hash,key1,val1, ... keyn,valn,[callback])
      • Client.hgetall (Hash,[callback])
    • Packaging to execute multiple commands [transaction]
    • Other...
Introduction and Installation
    • About Redis:
  1. Open source high-performance key-value storage, in-memory (in-memory) datasets, or disk storage (the former performance is high, but the data may be lost, the latter is the opposite)
  2. Supports high-speed operations on complex data structures by supporting strings (strings), hashes (hashes), lists (lists), collections (sets), and ordered collections (sorted sets).
  3. Features, support master-slave synchronization, pub/sub, etc.
  4. Supports multiple clients (http://redis.io/clients)
  5. ...

Note: The application scenario is not mentioned, there is not much practical experience, not nonsense, so as not to mislead people, but from its introduction and characteristics, at least the cache scene is good!

Redis:https://github.com/dmajkic/redis/downloads

node. JS Client: Node_redis https://github.com/mranney/node_redis/

    • Redis installation (Windows platform)

Redis is very convenient to download and unzip directly, because the development environment is Win7 64-bit, direct download (sample download of the installation package: Redis-2.4.5-win32-win64.zip)

    • Redis Run

Unzip to the Redis-server.exe in the "64bit" folder after running, but this will cause a warning to appear as follows:

  #Warning: no config file specified,using the default Config. In order to specify a config file use ' redis-server/path/to/redis.conf '

Hint is also obvious, there is no explicit configuration file, using the default configuration, please use ' redis-server/path/to/redis.conf ' to specify the explicit configuration file

Follow the prompts to run Redis success (e.g.)

In the Redis-server.exe sibling directory you can see a redis.conf file, which is the configuration file

    • Node_redis Installation
Installinstall Hiredis Redis

I'm using NPM install Hiredis Redis installation here

Note: Both are available, the difference is in performance, Hiredis is non-blocking, and faster, if the installation of Hiredis,node_redis will default to it as a parser, not installed will use a pure JavaScript interpreter, for learning or development environment, with which does not matter

Redis.createclient () Connect to Redis server

When the environment is ready, start writing a generation of simple code tests connect the server with Nodejs

var redis = require (' Redis '),    = redis.createclient (); Client.on (' ready ',function  (Err) {    console.log (' ready ');});
Sample Source Code

From which you can see the result of the run, output ready, indicating success!

Let's talk about the code:

  redis.createclient (): Returns a Redisclient object, which you can output to look at the specific information of this object.

  Ready : One of the connection events of Redis, which triggers this event when connected to a Redis server, indicates that the command is ready to be received and that the client command exists in the queue before the event is triggered, and is called sequentially when everything is ready.

For the above code can connect the successful Redis server, because the current Redis server is local, if not local, how to connect it?

var redis = require (' Redis '),    = 6379,        // port number    rds_host = ' 127.0.1.1 ',    // server IP    Rds_opts = {},            // Set Item    client = redis.createclient (rds_port,rds_host,rds_opts); Client.on (' ready ',function(res) {    console.log (' ready ');    });
Sample Source Code

and success! This approach and the previous one passed in port number, server IP, and setup entries at Redis.createclient ()

This allows you to connect to a remote Redis server, or use the third parameter for some configuration!

  default port for Redis : 6379

Certified Client.auth (password, callback)

The above tried, connected to the Redis server, we can see that we did not enter the password to verify the process is successfully connected to the server, because the Redis server does not require a password, but it is not very safe, we must set the password

Open redis.conf file, locate Requirepass, uncomment, set password to: Porschev

Requirepass Porschev

Then restart the Redis server and use the above code again to connect to the Redis server with an error message (e.g.): ERR operation not permitted

So how do I connect to a Redis server with a password?

A simple try, there are two ways (there may be more, did not try, in fact, a completely enough, more also useless ^_^!)

  Mode one: By setting the third parameter of Redis.createclient (), that is, setting the item to complete

var redis = require (' Redis '),    = 6379,        // port number    rds_host = ' 127.0.1.1 ',    // server IP    rds_pwd = ' Porschev ',    = {auth_pass:rds_pwd},            // Set Item    client =  Redis.createclient (rds_port,rds_host,rds_opts); Client.on (' ready ',function(res) {    Console.log (' ready ');    });
Sample Source Code

Can be connected successfully by setting the Auth_pass in the connection settings entry to pass the certification!

  auth_pass: The default value is NULL, the client will not connect through the AUTH command by default, and if this is set, the client will call the AUTH command to connect

  Way two: Through Client.auth (password, callback)

  = 6379, //  port number  Rds_host = ' 127.0 .1.1 ', //  server IP  rds_pwd = ' Porschev ', Span style= "color: #000000;" > rds_opts  = {}, //  set item  C Lient = Redis.createclient (rds_port,rds_host,rds_opts); Client.auth (Rds_pwd,  function   () {Console.log ( ' through authentication '  ' ready ', function   (RES) {    Console.log ( ' Ready ' ); });
Sample Source Code

This method can also be successful, the first parameter is the password, the second is the callback function!

Single-valued set and get

varRedis = require (' Redis '), Rds_port= 6379,//Port numberRds_host = ' 127.0.1.1 ',//Server IPrds_pwd = ' Porschev ',//PasswordRds_opts = {},//Setting ItemsClient =redis.createclient (rds_port,rds_host,rds_opts); Client.auth (Rds_pwd,function() {Console.log (' Through certification ');}); Client.on (' Connect ',function() {Client.set (' Author ', ' Wilson ', Redis.print); Client.get (' Author ', Redis.print); Console.log (' Connect ');}); Client.on (' Ready ',function(Err) {Console.log (' Ready ');});
Sample Source Code

As can be seen from the output, set a value and get this value are successful!

Code to say:

  Client.set (Key,value,[callback]): sets a single key and value, and the callback function is optional

  Client.get (Key,[callback]): get key to get value, callback function optional (although optional, but not write callback function to get what is the meaning of ^_^!)

  Connect: One of the connection events of Redis, in the case of not setting Client.options.no_ready_check, the client triggers connect and it emits ready, if set Client.options.no_ Ready_check, when this stream is connected, it triggers connect,

You're free to try to send a command.

Redis.print: A simple callback function that shows the return value when testing (as can be seen from the output of the example)

Other supplementary notes:

Client.options.no_ready_check: The default value is False, when connecting to a Redis server, the server may be loading the database from disk, and the Redis server will not respond to any commands while the loading phase is in progress. Node_redis will send a "ready to confirm" info command,

The info command responds by indicating that the server can provide the service at this time, and Node_redis will trigger the "Ready" event, and if the setting item is set to True, there will be no such check

Client.set ([key,value],callback): with Client.set (Key,value,[callback]), the effect is consistent (you can test the above example source code to modify, you must have a callback function

Multi-valued get and set

varRedis = require (' Redis '), Rds_port= 6379,//Port numberRds_host = ' 127.0.1.1 ',//Server IPrds_pwd = ' Porschev ',//PasswordRds_opts = {},//Setting ItemsClient =redis.createclient (rds_port,rds_host,rds_opts); Client.auth (Rds_pwd,function() {Console.log (' Through certification ');}); Client.on (' Connect ',function() {Client.hmset (' Short ', {' JS ': ' JavaScript ', ' C # ': ' C sharp '}, Redis.print); Client.hmset (' Short ', ' SQL ', ' structured Query Language ', ' HTML ', ' Hypertext mark-up Language ', Redis.print); Client.hgetall ("Short",function(err,res) {if(Err) {Console.log (' Error: ' +err); return;    } console.dir (res); });}); Client.on (' Ready ',function(Err) {Console.log (' Ready ');});
Sample Source Code

As you can see from the output, set multivalued and get are successful!

Code to say:

  Client.hmset (hash, obj, [callback]): An assignment operation, the first argument is a hash name, and the second argument is an object, where the key1:value1 is. , Keyn:valuen form; The third parameter is an optional callback function

  Client.hmset (hash, key1, Val1, ... Keyn, VALN, [callback]): The arguments before the 2nd parameter to the optional callback function are Key1, val1, ... Keyn, VALN form;

  Client.hgetall (hash, [callback]): Gets the value operation, returns an object

Other supplementary notes:

Console.dir (): used to display all properties and methods of an object

Packaging to execute multiple commands [transaction]

varRedis = require (' Redis '), Rds_port= 6379,//Port numberRds_host = ' 127.0.1.1 ',//Server IPrds_pwd = ' Porschev ',//PasswordRds_opts = {},//Setting ItemsClient =redis.createclient (rds_port,rds_host,rds_opts); Client.auth (Rds_pwd,function() {Console.log (' Through certification ');}); Client.on (' End ',function(Err) {Console.log (' End ');}); Client.on (' Connect ',function(){    varKey = ' skills '; Client.sadd (Key,' C # ', ' Java ', Redis.print); Client.sadd (Key,' Nodejs '); Client.sadd (Key,"MySQL"); Client.multi (). Sismember (Key,' C # '). Smembers (key). EXEC (function(err, replies) {Console.log ("MULTI got" + Replies.length + "replies"); Replies.foreach (function(reply, index) {console.log ("Reply" + Index + ":" +reply.tostring ());            });    Client.quit (); });});
Sample Source Code

The official has an example, I revise, may better understand some, the following step to say!

Check out the API and see the results first

  client.multi ([commands]): This marks the beginning of a transaction, performed by multi.exec atomicity; the description on GitHub is understandable as packaging, storing the commands to be executed in the queue, the Redis server atomically executing all the commands, the Node_redis interface returning a multi object

  Multi.exec (callback): executes all commands within a transaction; The description on GitHub is Client.multi () returns a Multi object that contains all the commands until Multi.exec () is called;

  Multi.exec (callback) callback function parameter err: Returns null or array, error returns an error message that occurs in the corresponding command sequence chain. The last element in this array is a Execabort type error originating from the exec itself

Multi.exec (callback) callback function parameter results: Returns null or array, returns the return information for each command in the command chain

End:triggered when a redis established connection is closed

  Client.sadd (key,value1,... valuen,[callback]): collection operation, adding n elements to the collection key, ignoring existing elements,adding only one value before the redis2.4 version

  Sismember (Key,value,[callback]): The element value exists in the collection key, there is a return of 1, there is no return 0

  smembers (Key,[callback]): returns all members of the collection key, the nonexistent collection key does not error, but is returned as an empty set

  client.quit (): There is a client.end () method corresponding to it, relatively violent ; The Client.quit method sends a QUIT command after all responses are received, while Client.end is closed directly; both trigger the end event

Look at the results should be more simple, Client.multi packaged sismember and smembers two commands, after executing the Exec method, the callback function to get two responses, respectively, output two response results!

Other...

  Redis.debug_mode: This may be useful in development, let's set the test to true, and then look at the output

  Publish/subscribe: This official example is relatively simple and clear, everyone run up to see it can understand, in-depth online there are many use it to implement the chat, monitoring examples, we look at, if you feel it necessary to do another example to share

  Client.monitor: monitoring, may be used in the future, there is a need for in-depth research, the introduction can be skipped

There are many other Redis commands that can be talked about very limited, in-depth exercises can be compared to: http://redis.readthedocs.org/en/latest/index.html

  Parameter data:

https://github.com/mranney/node_redis/

Http://redis.readthedocs.org/en/latest/index.html

http://dumbee.net/archives/114

Nodejs Learning Notes (ix)---Getting Started with redis interaction (Mranney/node_redis)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.