redis pub or sub nodejs

var redis = require(“redis”);var publisher = redis.createClient();publisher.publish(“notification”, “{\”message\”:\”Hello world from Asgardian!\”}”, function(){ process.exit(0);});

4
34
Matthew Bain 105 points

                                    // subscriber

const IORedis = require('ioredis')
const chalk = require('chalk')
const { Publisher } = require('./util.publisher')

class Subscriber {
	constructor(configs = { key: '' }) {
		this._key = configs.key
		this._keyFrom = Publisher.get()
	}

	_redisConnect() {
		const ioRedis = new IORedis({
			host: '127.0.0.1',
			port: 6379,
			maxRetriesPerRequest: 50,
			connectTimeout: 5000,
			enableReadyCheck: true,
			enableAutoPipelining: true
		})

		return ioRedis
	}

	async getString(keyName) {
		if (this._key == this._keyFrom) {
			const ioRedis = this._redisConnect()
			const response = await ioRedis.get(keyName)
			await ioRedis.expire(keyName, 60)
			if (response) {
				return Promise.resolve(response)
			}
			return {}
		} else {
			return Promise.reject(chalk.red(new Error(`invalid key Subscriber: ${this._key} and Publisher: ${this._keyFrom}`)))
		}
	}

	async getMap(keyName) {
		if (this._key == this._keyFrom) {
			const ioRedis = this._redisConnect()
			const response = await ioRedis.hgetall(keyName)
			await ioRedis.expire(keyName, 60)
			if (response) {
				return Promise.resolve(response)
			}
			return {}
		} else {
			return Promise.reject(chalk.red(new Error(`invalid key Subscriber: ${this._key} and Publisher: ${this._keyFrom}`)))
		}
	}

	async getArray(keyName) {
		if (this._key == this._keyFrom) {
			const ioRedis = this._redisConnect()
			const response = await ioRedis.hgetall(keyName)
			await ioRedis.expire(keyName, 60)
			if (response) {
				return Promise.resolve(JSON.parser(response).data)
			}
			return {}
		} else {
			return Promise.reject(chalk.red(new Error(`invalid key Subscriber: ${this._key} and Publisher: ${this._keyFrom}`)))
		}
	}

	async getResponse() {
		if (this._key == this._keyFrom) {
			const ioRedis = this._redisConnect()
			const response = await ioRedis.hgetall('message:speaker')
			await ioRedis.expire('message:speaker', 30)
			if (response) {
				return Promise.resolve(response)
			}
			return {}
		} else {
			return Promise.reject(chalk.red(new Error(`invalid key Subscriber: ${this._key} and Publisher: ${this._keyFrom}`)))
		}
	}
}

module.exports = { Subscriber }

4 (4 Votes)
0
0
12
Zelite 105 points

                                    more example redis pub/sub -> https://github.com/restuwahyu13/express-todo-redis

0
0
3.5
2

                                    var redis = require(“redis”);var subscriber = redis.createClient();subscriber.on(“message”, function (channel, message) { console.log(“Message: “ + message + “ on channel: “ + channel + “ is arrive!”);});subscriber.subscribe(“notification”);

3.5 (2 Votes)
0
0
1
B0nk3r 75 points

                                    // publisher

const IORedis = require('ioredis')

class Publisher {
	constructor(configs = { key: '' }) {
		this.key = configs.key
		Publisher.set(configs.key)
	}

	static get() {
		return this.key
	}

	static set(key = '') {
		this.key = key
	}

	_redisConnect() {
		const ioRedis = new IORedis({
			host: '127.0.0.1',
			port: 6379,
			maxRetriesPerRequest: 50,
			connectTimeout: 5000,
			enableReadyCheck: true,
			enableAutoPipelining: true
		})

		return ioRedis
	}

	async setString(keyName = '', data) {
		const ioRedis = _redisConnect()
		await ioRedis.set(keyName, data)
	}

	async setMap(keyName = '', data = {}) {
		const ioRedis = this._redisConnect()
		await ioRedis.hmset(keyName, { ...data })
	}

	async setArray(keyName = '', data = []) {
		const ioRedis = _redisConnect()
		await ioRedis.hmset(keyName, JSON.stringify({ data: data }))
	}

	async setResponse(data = {}) {
		const ioRedis = this._redisConnect()
		await ioRedis.hmset('message:speaker', { ...data })
	}
}

module.exports = { Publisher }

0
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source