是否可以在ZeroMQ中使用Subject?

时间:2017-11-29 09:19:03

标签: zeromq nats.io

我有一个实施NATS Queueing的小项目 这是代码:

import * as NATS from '../node_modules/nats'              // for typescript
var nats = require('nats');

var config = require('./config');
var opt: NATS.ClientOpts = {'noRandomize': false, 'reconnect': true, 
'maxReconnectAttempts': -1, 'servers':config.nat.servers, 'user': 
config.nat.user , 'pass': config.nat.pass };
var nc: NATS.Client = nats.connect(opt);

nc.on('error', function(e) {
    console.error('Error nats: ' + e);
});

nc.on('close', function() {
    console.error('CLOSED nats');
});

nc.subscribe('serviceA', { 'queue': 'A' }, function (request, replyTo) {
    console.debug('I exec serviceA via nats:');
    j = JSON.parse(request);
    console.debug(j);
    let ok = {"res": "i am response for service A"}
    nc.publish(replyTo, JSON.stringify(ok));
}

let cmd = '{"a": 5, "b": "i am sample"}';
nc.requestOne('serviceA', cmd, {}, 15000, function (response) {
    if (response.code && response.code === nats.REQ_TIMEOUT) {
        console.error('server timeout');
        console.error(response.code);
    } else {
        console.log('A see this response: ' + response);
    }
});

nc.subscribe('serviceB', { 'queue': 'B' }, function (request, replyTo) {
    console.debug('I exec serviceB via nats:');
    j = JSON.parse(request);
    console.debug(j);
    let ok = {"res": "i am response for service B"}
    nc.publish(replyTo, JSON.stringify(ok));
}

let cmd = '{"c": 5, "d": "i am sample"}';
nc.requestOne('serviceB', cmd, {}, 15000, function (response) {
    if (response.code && response.code === nats.REQ_TIMEOUT) {
        console.error('server timeout');
        console.error(response.code);
    } else {
        console.log('B see this response: ' + response);
    }
});

如您所见,队列 serviceA A 有2项服务 - serviceB strong>队列 B 和2个客户端:第一个呼叫服务A,第二个呼叫服务B

NATS实现主题('serviceA''serviceB'

现在,我想尝试使用ØMQ转换示例我发现使用ZeroMQ的类似示例

但我在主题上找不到任何样本。

也许ØMQ使用ROUTER来实现主题

您能帮助我将主题实施到ZeroMQ示例中吗?

1 个答案:

答案 0 :(得分:2)

问:是否可以在ZeroMQ中使用主题?
答:是的,它是:

长话短说 - 一个人不需要任何zmq.ROUTER这样做,只需使用PUB / SUB正式模式。

注意: ZeroMQ Socket() - 实例一个tcp-socket-as-know-it-it。

最佳
阅读 [ZeroMQ hierarchy in less than a five seconds] 部分中的主要概念差异

发布者方:

import zmq
aCtx = zmq.Context()
aPub = aCtx.Socket( zmq.PUB )
aPub.bind( "tcp://123.456.789.012:3456" )
aPub.setsockopt(    zmq.LINGER,   0 )
aPub.setsockopt(    zmq.<whatever needed to fine-tune the instance>, <val> )
i = 0
while true:
      try:
         aPub.send( "ServiceA::[#{0:_>12d}] a Hello World Message.".format( i ) )
         aPub.send( "ServiceABCDEFGHIJKLMNOPQRSTUVWXYZ........" )
         aPub.send( "ServiceB::[#{0:_>12d}] another message...".format( i  / 2 ) ) if ( i == ( 2 * ( i / 2 ) ) ) else pass
         sleep( 1 ); i += 1

      except KeyboardInterrupt:
          print( "---< will exit >---" )
          break
print( "---< will terminate ZeroMQ resources >---" )
aPub.close()
aCtx.term()

订阅方:

import zmq
aCtx = zmq.Context()
aSub = aCtx.Socket( zmq.SUB )
aSub.connect( "tcp://123.456.789.012:3456" )
aSub.setsockopt( zmq.LINGER, 0 )
aSub.setsockopt( zmq.SUBSCRIBE, "ServiceA" ) # Subject ( 'serviceA' and 'serviceB' ) 
aSub.setsockopt( zmq.SUBSCRIBE, "ServiceB" ) # Kindly see the comments below
#                                            # Kindly see API on subscription management details
#
#                                            # Yet another "dimension"
#                                            #     to join ingress
#                                            #     from multiple sources
#Sub.connect( "<transport-class>://<addr>:<port>" )
#              <transport-class :: { inproc | ipc | tcp | pgm | epgm | vmci }
#   .connect()-s the same local SUB-AccessPoint to another PUB-side-AccessPoint
#                to allow the PUB/SUB Scalable Formal Communication Archetype Pattern
#                join a message flow from different source PUB-sides
#Sub.setsockopt( zmq.SUBSCRIBE, "ServiceZ" )

while true:
      try:
          print( "<<< (((_{0:s}_)))".format( aSub.recv() ) )
      except KeyboardInterrupt:
          print( "---< will exit >---" )
          break

print( "---< will terminate ZeroMQ resources >---" )
aSub.close()
aCtx.term()