zoukankan      html  css  js  c++  java
  • nodejs使用redis实现sub/pub

    1、为了测试,在windows系统安装redis

      参考:windows安装解压版redis

    demo结构:

    2、代码

      pageage.json

    {
      "name": "redis_pub_sub_demo",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "pg": "^7.14.0",
        "redis": "^2.8.0"
      },
      "devDependencies": {
        "webpack-dev-server": "^3.9.0"
      }
    }

      dbConfig.js

    const pg = require('pg')
    
    // 数据库配置
    var config = {
        user: "wenbin.ouyang",
        host: 'localhost',
        database: "test",
        password: "root",
        port: 5432,
    
        // 扩展属性
        max: 20, // 连接池最大连接数
        idleTimeoutMillis: 3000, // 连接最大空闲时间 3s
    }
    
    // 创建连接池
    var pool = new pg.Pool(config)
    
    module.exports = pool

       sub.js

    var redis = require("redis");
    var pool = require('./dbConfig.js');
    
    var client = redis.createClient(6379, '127.0.0.1', { connect_timeout: 100 })
    // 订阅频道:mychannel
    client.subscribe("mychannel", function (e) {
        console.log('subscribe channel: mychannel');
    });
    
    client.on("message", function (channel, res) {
        console.log('channel: ', channel)
        console.log(typeof res) // string
        console.log('res:', res);
        var obj = JSON.parse(res) // 转成jsonobj
        console.log(obj.id + "  " + obj.name + "  " + obj.age)
    
        // 插入数据库
        pool.connect().then(client => {
            // insert 数据
            client.query("INSERT INTO student(name, age) VALUES($1::varchar, $2::int)", [obj.name, obj.age], (err, res) => {
                console.log(err ? err.stack : res)
                if (err) return false
                client.release()
                return true
            })
        })
    });
    
    client.on("error", function (err) {
        console.log("response err:" + err)
    });

      pub.js

    var redis = require("redis")
    var redisClient = redis.createClient(6379, '127.0.0.1')
    // redisClient.auth('')
    
    var msg1 = { id: 1, name: '王昭君aaa', age: '20' };
    redisClient.publish('mychannel', JSON.stringify(msg1))
    
    redisClient.info(function (err, response) {
        console.log(err, response)
    });

      

    3、测试

      1)先执行命令 node  .sub.js监听订阅频道

      2)然后执行node .pub.js 发布消息

    redis启动:

    redis客户端,订阅subscribe mychannel

     ---

  • 相关阅读:
    【方法1】删除Map中Value反复的记录,而且仅仅保留Key最小的那条记录
    hdu3415 Max Sum of Max-K-sub-sequence 单调队列
    HBase总结(十八)Hbase rowkey设计一
    Makefile生成器,使用C++和Boost实现
    quartz cron表达式在线生成
    NS3网络仿真(6): 总线型网络
    连载:面向对象葵花宝典:思想、技巧与实践(35)
    zoj 2921 Stock(贪心)
    11g RAC 加节点 之 手动加入vip 资源
    [Unity3D]Unity+Android交互教程——让手机"动"起来
  • 原文地址:https://www.cnblogs.com/xy-ouyang/p/12321543.html
Copyright © 2011-2022 走看看