feat: initialize microservice architecture with auth, api, realtime, copernicus, ml, and console modules
This commit is contained in:
79
realtime/src/helper/redis.js
Normal file
79
realtime/src/helper/redis.js
Normal file
@@ -0,0 +1,79 @@
|
||||
const Redis = require('ioredis');
|
||||
|
||||
const redis = new Redis({
|
||||
host: process.env.REDIS_HOST,
|
||||
port: process.env.REDIS_PORT
|
||||
});
|
||||
|
||||
// Client dedicato per subscribe (ioredis richiede client separato)
|
||||
const redisSub = new Redis({
|
||||
host: process.env.REDIS_HOST,
|
||||
port: process.env.REDIS_PORT
|
||||
});
|
||||
|
||||
redis.on('error', (error) => {
|
||||
console.error('Redis error:', error);
|
||||
});
|
||||
|
||||
redis.on('connect', () => {
|
||||
console.log('Server connected to Redis DB');
|
||||
});
|
||||
|
||||
redisSub.on('error', (error) => {
|
||||
console.error('Redis sub error:', error);
|
||||
});
|
||||
|
||||
const sensors_hash_map = 'sensors:sessions';
|
||||
|
||||
async function setSession(sensorID, metadata) {
|
||||
await redis.hset(sensors_hash_map, sensorID, JSON.stringify(metadata));
|
||||
}
|
||||
|
||||
async function getSession(sensorID) {
|
||||
return await redis.hget(sensors_hash_map, sensorID);
|
||||
}
|
||||
|
||||
async function deleteSession(sensorID) {
|
||||
await redis.hdel(sensors_hash_map, sensorID);
|
||||
}
|
||||
|
||||
async function getSessions() {
|
||||
return await redis.hgetall(sensors_hash_map);
|
||||
}
|
||||
|
||||
// --- Pub/Sub per live watchers ---
|
||||
|
||||
async function publishSensorData(sensorId, data) {
|
||||
await redis.publish(`sensor:data:${sensorId}`, JSON.stringify(data));
|
||||
}
|
||||
|
||||
async function addWatcher(sensorId) {
|
||||
return await redis.incr(`sensor:watchers:${sensorId}`);
|
||||
}
|
||||
|
||||
async function removeWatcher(sensorId) {
|
||||
const count = await redis.decr(`sensor:watchers:${sensorId}`);
|
||||
if (count <= 0) {
|
||||
await redis.del(`sensor:watchers:${sensorId}`);
|
||||
return 0;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function getWatcherCount(sensorId) {
|
||||
const count = await redis.get(`sensor:watchers:${sensorId}`);
|
||||
return parseInt(count) || 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
setSession,
|
||||
getSession,
|
||||
deleteSession,
|
||||
getSessions,
|
||||
publishSensorData,
|
||||
addWatcher,
|
||||
removeWatcher,
|
||||
getWatcherCount,
|
||||
redis,
|
||||
redisSub
|
||||
};
|
||||
Reference in New Issue
Block a user