使用node_redis進行redis數據庫crud操做

正在學習使用pomelo開發遊戲服務器,碰到node.js操做redis,記錄一下node

假設應用場景是操做一個用戶表的數據redis

引入node_redis庫,建立客戶端服務器

var redis  = require("redis");
var client = redis.createClient();

 

建立用戶數據學習

var players = new Array();

players.push({"id":49, "name":"test player11","vip":12,"rmb":23,"psd":"password1234"});
players.push({"id":932, "name":"test player12","vip":11,"rmb":23,"psd":"password1234"});
players.push({"id":936, "name":"test player13","vip":10,"rmb":23,"psd":"password1234"});
players.push({"id":626, "name":"test player14","vip":9,"rmb":23,"psd":"password1234"});

var player;
client.get('uidx', function (err, uidx)
{
    for(var i = 0; i < players.length; ++i)
    {
        client.incr('uidx');
        uidx++;

        player = players[i];

        client.hmset("user:"+ uidx, player
            , function (err) {
            });

        // client.hmset("user:"+ uidx
        //     ,'userId', player.id
        //     ,'username',player.name
        //     ,'password', player.psd
        //     , function (err) {
        //     });

        client.hmset("userId:"+ player.id
            ,'uidx', uidx
            , function (err) {
            });
    }
});

 

根據玩家編號查詢ui

var playerID = 49;
client.hget('userId:'+ playerID, 'uidx', function(err, uidxQuery){
    if (err)
    {
        console.log(err);
        return;
    }
    else
    {
        //client.hget('user:'+ uidxQuery, 'username', function (err, username) {
        client.hgetall('user:'+ uidxQuery, function (err1, user) {
            if (err1)
            {
                console.log(err);
                return;
            }
            else
            {
                if (user)
                {
                    console.log(user.username);
                }
                else
                {
                    console.log("no user id is " + playerID);
                }
            }
        })
    }
});

 

根據玩家編號更新數據spa

var playerID = 49;
var player = {"id":49, "name":"angle","vip":81,"rmb":41,"psd":"waitforu"};
client.hget('userId:'+ playerID, 'uidx', function(err, uidx)
{
    if (err)
    {
        console.log(err);
        return;
    }
    else
    {
        client.hmset("user:"+ uidx, player, redis.print);
    }
});

 

根據玩家編號刪除數據code

var playerID = 49;
client.hget('userId:'+ playerID, 'uidx', function(err, uidx)
{
    if (err)
    {
        console.log(err);
        return;
    }
    else
    {
        client.del("user:"+ uidx);
        client.del('userId:'+ playerID);
    }
});
相關文章
相關標籤/搜索