redis使用例子和net模块

来源:互联网 发布:sql over partition by 编辑:程序博客网 时间:2024/06/06 15:39

关闭redis的持久化操作,只需要在redis启动的配置文件里,将save项全注释掉

var redis = require('redis');var client = redis.createClient(6379, '127.0.0.1');client.on('error', function (err) {console.log('Error' + err);});client.set('color', 'red', redis.print);client.get('color', function(err, value) {if (err) throw err;console.log('Got: ' + value);});/* 2.用哈希表存放数据 */// 用哈希表存储和获取数据client.hmset('camping', {'shelter': '2-person tent','cooking': 'campstove'}, redis.print);// 获取元素cooking的值client.hget('camping', 'cooking', function(err, value) {if (err) throw err;console.log('Will be cooking with: ' + value);});// 获取哈希表的键client.hkeys('camping', function(err, keys) {if (err) throw err;keys.forEach(function(key, i) {console.log(' ' + key);});});/* 3.用链表存储和获取数据 */// lpush向键表中添加值client.lpush('tasks', 'Paint the bikeshed red.', redis.print);client.lpush('tasks', 'Paint the bikeshed green.', redis.print);// 获取参数start和end范围内的链表元素client.lrange('tasks', 0, -1, function(err, items) {if (err) throw err;items.forEach(function(item, i) {console.log(' ' + item);});});/* 4.用集合存储和获取数据 */client.sadd('ip_addresses', '192.168.1.1', redis.print);client.sadd('ip_addresses', '192.168.1.1', redis.print);client.sadd('ip_addresses', '192.168.1.2', redis.print);client.smembers('ip_addresses', function(err, members) {if (err) throw err;console.log(members);});/* 5.用信道传递数据 */// Redis客户端可以向任一给定的信道预订或发布消息.预订一个信道意味着你会收到所有发送给它的消息,发布给信道的消息会发送给所有预订了那个信道的客户端// 用Redis的发布/预订功能实现简单聊天服务器var net = require('net');var server = net.createServer(function(socket) {var subscriber;var publisher;socket.on('connect', function() {// 为用户创建预订客户端subscriber = redis.createClient();// 预订信道subscriber.subscribe('main_chat_room');// 信道收到消息后把它发给用户subscriber.on('message', function(channel, message) {socket.write('Channel ' + channel + ': ' + message);});// 为用户创建发布客户端publisher = redis.createClient();});socket.on('data', function(data) {// 用户输入消息后发布它publisher.publish('main_chat_room', data);});socket.on('end', function() {subscriber.unsubscribe('main_chat_room');subscriber.end();publisher.end();});});server.listen(3000);

0 0
原创粉丝点击