• Nodejs使用redis


    安装方法

    安装redis方法请自行百度,

    npm方法,安装nodejsredis模块

    npm install redis  

    实战

    var redis = require("redis") ,
    client = redis.createClient();
    
    client.on("error", function (err) {
        console.log("Error " + err);
    });
      
    //链接redis_name表
    client.on("connect", redis_name);
     
     
    function runSample() {
         //使用set 对key 进行赋值,
          client.set("key", "Hello World", function (err, reply) {
               console.log(reply.toString());
          });
         //使用get 获取key的值
         client.get("key", function (err, reply) {
              console.log(reply.toString());
          });
    }

    同时可用expire来设置对象失效时间

    //设置key的失效时间
    client.expire('key', 3);  

    下面是redis 实战完整代码,可供参考 

    var redis = require("redis"),//召唤redis  
    /* 
        连接redis数据库,createClient(port,host,options); 
        如果REDIS在本机,端口又是默认,直接写createClient()即可 
        redis.createClient() = redis.createClient(7788, '127.0.0.1', {}) 
    */  
    client = redis.createClient(7788,'192.168.159.128',{});  
    //如果需要验证,还要进行验证  
    //client.auth(password, callback);  
      
    // if you'd like to select database 3, instead of 0 (default), call  
    // client.select(3, function() { /* ... */ });  
      
    //错误监听?  
    client.on("error", function (err) {  
        console.log("Error " + err);  
    });  
      
    client.set("string key", "string val", redis.print);//set "string key" "string val"  
    /* 
        redis.print,回调函数,将redis的返回值显示出来。上一句执行结果,将返回“OK”  
    */  
    client.hset("hash key", "hashtest 1", "some value", redis.print);  
    client.hset(["hash key", "hashtest 2", "some other value"], redis.print);  
    //遍历哈希表"hash key"  
    client.hkeys("hash key", function (err, replies) {  
        console.log(replies.length + " replies:");  
        replies.forEach(function (reply, i) {  
            console.log("    " + i + ": " + reply);  
        });  
    client.hget("hash key","hashtest 1",redis.print);      
      
    /*两种都可以断掉与redis的连接, 
    end()很粗暴,不管3721,一下子退出来了,上面那句获取哈希表"hash key"的某个元素值的表达式将没有结果返回 
    而quit()则是先将语句处理完毕再干净地退出,斯文得很 
    */  
    //client.end();  
    client.quit();  
    });  
    

      

  • 相关阅读:
    1、听说过Redis吗?它是什么?
    55、数据库高并发是我们经常会遇到的,你有什么好的解决方案吗?
    54、数据库如何保证持久性?
    53、数据库如何保证原子性?
    52、数据库如何保证一致性?
    注解定义、基本语法和属性
    Macbook 装机必备--开发篇
    http
    python:beaufiful
    python-yield
  • 原文地址:https://www.cnblogs.com/peiyu1988/p/6688187.html
Copyright © 2020-2023  润新知