2016-12-12 3 views
1

nodejs의 redis에서 변경된 값 이벤트를 수신 할 수 있습니까?NodeJS Redis Listener

상황 : 내가 다른 응용 프로그램에서 실시간으로 데이터를 표시하는 NodeJS 응용 프로그램이 (동일한 서버에 네이티브 응용 프로그램을, 노드 응용 프로그램 막대를 호출 foo를 호출하고 할 수 있습니다).

Foo는 시스템 상태를 redis 키 "state"에 저장합니다. Bar가이를 등록하고 표시합니다. 이 사건을 어떻게 포착 할 수 있습니까?

편집 Pierres Solution은 키를 가져 오는 데는 문제가 없지만 값을 검색하는 방법은 무엇입니까? 내가이 방법을 시도했다, 그러나 parseError가 발생

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

client_redis.config('set', 'notify-keyspace-events', 'KEA'); 
client_redis.subscribe('[email protected]__:set'); 
client_redis.on('message', function(channel, key) { 
    client_redis.get(key, function(error, result) { 
    if (error) console.log(error); 
    else console.log(result); 
    }); 
}); 

오류

$ { ReplyError> at parseError (/home/pi/Website/node_modules/redis-parser/lib/parser.js:181:12) -bash: syntax error near unexpected token `(' 

편집 # 2 그것은 해당 값을 읽는 client_redis.subscribe('...') 블록 클라이언트처럼 보인다

열쇠. 값을 읽는 두 번째 클라이언트를 추가했습니다.

작업 예 :

var redis = require("redis"); 
// Client for subscription 
var subscriptionClient = redis.createClient(); 
// Client for reading the values from the keys. 
var readClient = redis.createClient(); 


subscriptionClient.config('set', 'notify-keyspace-events', 'KEA'); 
// subscribe to the key event so we get notificated if a value changes 
subscriptionClient.subscribe('[email protected]__:set'); 

subscriptionClient.on('message', function(channel, key) { 
    readClient.get(key, function(err, value) { 
    console.log(value); 
    }); 
}); 
+0

예, 두 번째 레디 스 클라이언트를 추가해야합니다. Redis 클라이언트가 구독자 모드에 들어가면 더 많은 채널을 구독하거나 구독 된 구독을 구독 취소하는 것 이외의 다른 작업을 더 이상 수행 할 수 없습니다. –

답변

3

네, 가능합니다. Redis Keyspace Notifications을 사용해야합니다.

특히 을 참조하십시오. 다른 명령 부분으로 생성되는 이벤트. 당신은 아마 SET 명령을 사용할 때 통지 :

var redis = require('redis'); 
var client_redis = redis.createClient(); 

// enable notify-keyspace-events for all kind of events (can be refined) 
client_redis.config('set','notify-keyspace-events','KEA'); 

client_redis.subscribe('[email protected]__:set'); 
// you can target a specific key with a second parameter 
// example, client_redis.subscribe('[email protected]__:set', 'mykey') 

client_redis.on('message', function(channel, key) { 
    // do what you want when a value is updated 
}); 
+1

답변을 업데이트했습니다. –

+0

필자는 필자의 질문에 편집 부분을 추가했습니다. 지금까지 고마워요, charme 같은 핵심 작품을 찾아내는하지만 내 값을 검색 할 수 있도록 구문 분석 오류를 제거하는 방법을 알고 계십니까? – FRules

관련 문제