rabbitMq动态创建和监听队列_rabbitmq动态创建队列

* @return org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer
*/
@Bean
public SimpleMessageListenerContainer messageContainer(ConnectionFactory connectionFactory) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
return container;
}
}


##### 消息监听处理类



@Component
public class MessageListenerImpl implements MessageListener {
private static final Logger logger = LoggerFactory.getLogger(MessageListenerImpl.class);
@Override
public void onMessage(Message message) {
try {
String mes = new String(message.getBody(), “utf-8”);
logger.info(“监听到消息:{}”,mes);
//todo 业务处理
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}


##### 动态添加监听



@Autowired
private SimpleMessageListenerContainer container;
@Autowired
private MessageListenerImpl message;
@Override
public void addListener(String queueName) {
    //获取当前监听的队列名称
    String[] strings=container.getQueueNames();
    List<String> list=Arrays.asList(strings);
    if (!list.contains(queueName)) {
        container.addQueueNames(queueName);
        //设置消息监听处理类
        container.setMessageListener(message);
    }
}

#### 前端js监听并消费


##### 引入stomp.js(cv大法或者自己引入)



// Generated by CoffeeScript 1.7.1
/*
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright © 2010-2013 Jeff Mesnil
Copyright © 2012 FuseSource, Inc.
*/
(function() {
var Byte, Client, Frame, Stomp,
__hasProp = {}.hasOwnProperty,
__slice = [].slice;

Byte = {
LF: ‘\x0A’,
NULL: ‘\x00’
};

Frame = (function() {
var unmarshallSingle;

function Frame(command, headers, body) {
  this.command = command;
  this.headers = headers != null ? headers : {};
  this.body = body != null ? body : '';
}

Frame.prototype.toString = function() {
  var lines, name, skipContentLength, value, _ref;
  lines = [this.command];
  skipContentLength = this.headers['content-length'] === false ? true : false;
  if (skipContentLength) {
    delete this.headers['content-length'];
  }
  _ref = this.headers;
  for (name in _ref) {
    if (!\_\_hasProp.call(_ref, name)) continue;
    value = _ref[name];
    lines.push("" + name + ":" + value);
  }
  if (this.body && !skipContentLength) {
    lines.push("content-length:" + (Frame.sizeOfUTF8(this.body)));
  }
  lines.push(Byte.LF + this.body);
  return lines.join(Byte.LF);
};

Frame.sizeOfUTF8 = function(s) {
  if (s) {
    return encodeURI(s).match(/%..|./g).length;
  } else {
    return 0;
  }
};

unmarshallSingle = function(data) {
  var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;
  divider = data.search(RegExp("" + Byte.LF + Byte.LF));
  headerLines = data.substring(0, divider).split(Byte.LF);
  command = headerLines.shift();
  headers = {};
  trim = function(str) {
    return str.replace(/^\s+|\s+$/g, '');
  };
  _ref = headerLines.reverse();
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    line = _ref[_i];
    idx = line.indexOf(':');
    headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
  }
  body = '';
  start = divider + 2;
  if (headers['content-length']) {
    len = parseInt(headers['content-length']);
    body = ('' + data).substring(start, start + len);
  } else {
    chr = null;
    for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {
      chr = data.charAt(i);
      if (chr === Byte.NULL) {
        break;
      }
      body += chr;
    }
  }
  return new Frame(command, headers, body);
};

Frame.unmarshall = function(datas) {
  var data;
  return (function() {
    var _i, _len, _ref, _results;
    _ref = datas.split(RegExp("" + Byte.NULL + Byte.LF + "\*"));
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      data = _ref[_i];
      if ((data != null ? data.length : void 0) > 0) {
        _results.push(unmarshallSingle(data));
      }
    }
    return _results;
  })();
};

Frame.marshall = function(command, headers, body) {
  var frame;
  frame = new Frame(command, headers, body);
  return frame.toString() + Byte.NULL;
};

return Frame;

})();

Client = (function() {
var now;

function Client(ws) {
  this.ws = ws;
  this.ws.binaryType = "arraybuffer";
  this.counter = 0;
  this.connected = false;
  this.heartbeat = {
    outgoing: 10000,
    incoming: 10000
  };
  this.maxWebSocketFrameSize = 16 \* 1024;
  this.subscriptions = {};
}

Client.prototype.debug = function(message) {
  var _ref;
  return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? _ref.log(message) : void 0 : void 0;
};

now = function() {
  if (Date.now) {
    return Date.now();
  } else {
    return new Date().valueOf;
  }
};

Client.prototype.\_transmit = function(command, headers, body) {
  var out;
  out = Frame.marshall(command, headers, body);
  if (typeof this.debug === "function") {
    this.debug(">>> " + out);
  }
  while (true) {
    if (out.length > this.maxWebSocketFrameSize) {
      this.ws.send(out.substring(0, this.maxWebSocketFrameSize));
      out = out.substring(this.maxWebSocketFrameSize);
      if (typeof this.debug === "function") {
        this.debug("remaining = " + out.length);
      }
    } else {
      return this.ws.send(out);
    }
  }
};

Client.prototype.\_setupHeartbeat = function(headers) {
  var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;
  if ((_ref = headers.version) !== Stomp.VERSIONS.V1\_1 && _ref !== Stomp.VERSIONS.V1\_2) {
    return;
  }
  _ref1 = (function() {
    var _i, _len, _ref1, _results;
    _ref1 = headers['heart-beat'].split(",");
    _results = [];
    for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
      v = _ref1[_i];
      _results.push(parseInt(v));
    }
    return _results;
  })(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];
  if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {
    ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
    if (typeof this.debug === "function") {
      this.debug("send PING every " + ttl + "ms");
    }
    this.pinger = Stomp.setInterval(ttl, (function(\_this) {
      return function() {
        _this.ws.send(Byte.LF);
        return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;
      };
    })(this));
  }
  if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {
    ttl = Math.max(this.heartbeat.incoming, serverOutgoing);
    if (typeof this.debug === "function") {
      this.debug("check PONG every " + ttl + "ms");
    }
    return this.ponger = Stomp.setInterval(ttl, (function(\_this) {
      return function() {
        var delta;
        delta = now() - _this.serverActivity;
        if (delta > ttl \* 2) {
          if (typeof _this.debug === "function") {
            _this.debug("did not receive server activity for the last " + delta + "ms");
          }
          return _this.ws.close();
        }
      };
    })(this));
  }
};

Client.prototype.\_parseConnect = function() {
  var args, connectCallback, errorCallback, headers;
  args = 1 <= arguments.length ? \_\_slice.call(arguments, 0) : [];
  headers = {};
  switch (args.length) {
    case 2:
      headers = args[0], connectCallback = args[1];
      break;
    case 3:
      if (args[1] instanceof Function) {
        headers = args[0], connectCallback = args[1], errorCallback = args[2];
      } else {
        headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];
      }
      break;
    case 4:
      headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];
      break;
    default:
      headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];
  }
  return [headers, connectCallback, errorCallback];
};

Client.prototype.connect = function() {
  var args, errorCallback, headers, out;
  args = 1 <= arguments.length ? \_\_slice.call(arguments, 0) : [];
  out = this.\_parseConnect.apply(this, args);
  headers = out[0], this.connectCallback = out[1], errorCallback = out[2];
  if (typeof this.debug === "function") {
    this.debug("Opening Web Socket...");
  }
  this.ws.onmessage = (function(\_this) {
    return function(evt) {
      var arr, c, client, data, frame, messageID, onreceive, subscription, _i, _len, _ref, _results;
      data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, ((function() {
        var _i, _len, _results;
        _results = [];
        for (_i = 0, _len = arr.length; _i < _len; _i++) {
          c = arr[_i];
          _results.push(String.fromCharCode(c));
        }
        return _results;
      })()).join('')) : evt.data;
      _this.serverActivity = now();
      if (data === Byte.LF) {
        if (typeof _this.debug === "function") {
          _this.debug("<<< PONG");
        }
        return;
      }
      if (typeof _this.debug === "function") {
        _this.debug("<<< " + data);
      }
      _ref = Frame.unmarshall(data);
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        frame = _ref[_i];
        switch (frame.command) {
          case "CONNECTED":
            if (typeof _this.debug === "function") {
              _this.debug("connected to server " + frame.headers.server);
            }
            _this.connected = true;
            _this.\_setupHeartbeat(frame.headers);
            _results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);
            break;
          case "MESSAGE":
            subscription = frame.headers.subscription;
            onreceive = _this.subscriptions[subscription] || _this.onreceive;
            if (onreceive) {
              client = _this;
              messageID = frame.headers["message-id"];
              frame.ack = function(headers) {
                if (headers == null) {
                  headers = {};
                }
                return client.ack(messageID, subscription, headers);
              };
              frame.nack = function(headers) {
                if (headers == null) {
                  headers = {};
                }
                return client.nack(messageID, subscription, headers);
              };
              _results.push(onreceive(frame));
            } else {
              _results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);
            }
            break;
          case "RECEIPT":
            _results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);
            break;
          case "ERROR":
            _results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);
            break;
          default:
            _results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);
        }
      }
      return _results;
    };
  })(this);
  this.ws.onclose = (function(\_this) {
    return function() {
      var msg;
      msg = "Whoops! Lost connection to " + _this.ws.url;
      if (typeof _this.debug === "function") {
        _this.debug(msg);
      }
      _this.\_cleanUp();
      return typeof errorCallback === "function" ? errorCallback(msg) : void 0;
    };
  })(this);
  return this.ws.onopen = (function(\_this) {
    return function() {
      if (typeof _this.debug === "function") {
        _this.debug('Web Socket Opened...');
      }
      headers["accept-version"] = Stomp.VERSIONS.supportedVersions();
      headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');
      return _this.\_transmit("CONNECT", headers);
    };
  })(this);
};

Client.prototype.disconnect = function(disconnectCallback, headers) {
  if (headers == null) {
    headers = {};
  }
  this.\_transmit("DISCONNECT", headers);
  this.ws.onclose = null;
  this.ws.close();
  this.\_cleanUp();
  return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;
};

Client.prototype.\_cleanUp = function() {
  this.connected = false;
  if (this.pinger) {
    Stomp.clearInterval(this.pinger);
  }
  if (this.ponger) {
    return Stomp.clearInterval(this.ponger);
  }
};

Client.prototype.send = function(destination, headers, body) {
  if (headers == null) {
    headers = {};
  }
  if (body == null) {
    body = '';
  }
  headers.destination = destination;
  return this.\_transmit("SEND", headers, body);
};

Client.prototype.subscribe = function(destination, callback, headers) {
  var client;
  if (headers == null) {
    headers = {};
  }
  if (!headers.id) {
    headers.id = "sub-" + this.counter++;
  }
  headers.destination = destination;
  this.subscriptions[headers.id] = callback;
  this.\_transmit("SUBSCRIBE", headers);
  client = this;
  return {
    id: headers.id,
    unsubscribe: function() {
      return client.unsubscribe(headers.id);
    }
  };
};

Client.prototype.unsubscribe = function(id) {
  delete this.subscriptions[id];
  return this.\_transmit("UNSUBSCRIBE", {
    id: id
  });
};

Client.prototype.begin = function(transaction) {
  var client, txid;
  txid = transaction || "tx-" + this.counter++;
  this.\_transmit("BEGIN", {
    transaction: txid
  });
  client = this;
  return {
    id: txid,
    commit: function() {
      return client.commit(txid);
    },
    abort: function() {
      return client.abort(txid);
    }
  };
};

Client.prototype.commit = function(transaction) {
  return this.\_transmit("COMMIT", {
    transaction: transaction
  });
};

Client.prototype.abort = function(transaction) {
  return this.\_transmit("ABORT", {
    transaction: transaction
  });
};

Client.prototype.ack = function(messageID, subscription, headers) {
  if (headers == null) {
    headers = {};
  }
  headers["message-id"] = messageID;
  headers.subscription = subscription;
  return this.\_transmit("ACK", headers);
};

Client.prototype.nack = function(messageID, subscription, headers) {
  if (headers == null) {
    headers = {};
  }
  headers["message-id"] = messageID;
  headers.subscription = subscription;
  return this.\_transmit("NACK", headers);
};

return Client;

})();

Stomp = {
VERSIONS: {
V1_0: ‘1.0’,
V1_1: ‘1.1’,
V1_2: ‘1.2’,
supportedVersions: function() {
return ‘1.1,1.0’;
}
},
client: function(url, protocols) {
var klass, ws;
if (protocols == null) {
protocols = [‘v10.stomp’, ‘v11.stomp’];
}
klass = Stomp.WebSocketClass || WebSocket;
ws = new klass(url, protocols);
return new Client(ws);
},
over: function(ws) {
return new Client(ws);
},
Frame: Frame
};

if (typeof exports !== “undefined” && exports !== null) {
exports.Stomp = Stomp;
}

if (typeof window !== “undefined” && window !== null) {
Stomp.setInterval = function(interval, f) {
return window.setInterval(f, interval);
};
Stomp.clearInterval = function(id) {
return window.clearInterval(id);
};
window.Stomp = Stomp;

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数大数据工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年大数据全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上大数据开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注大数据获取)
img

,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!**

因此收集整理了一份《2024年大数据全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
[外链图片转存中…(img-hCGVySpf-1712858385230)]
[外链图片转存中…(img-jaUGd6CF-1712858385230)]
[外链图片转存中…(img-FYqXkfia-1712858385231)]
[外链图片转存中…(img-7yEaM9HM-1712858385231)]
[外链图片转存中…(img-r2r5wWGs-1712858385231)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上大数据开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注大数据获取)
[外链图片转存中…(img-1QVpqbFq-1712858385232)]

  • 17
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用C++创建RabbitMQ消费者并监听model_1队列,可以使用RabbitMQ C++客户端库(AMQP-CPP)。 以下是一个简单的示例代码,可以连接到RabbitMQ服务器并监听队列: ```cpp #include <iostream> #include <amqpcpp.h> #include <amqpcpp/libboostasio.h> using namespace std; int main() { // 创建一个事件循环对象 boost::asio::io_service service; // 创建一个TCP连接对象 auto tcp = boost::make_shared<amqp::tcp_socket>(boost::ref(service)); // 连接到RabbitMQ服务器 amqp::connection connection(tcp, amqp::connection::make_plain("localhost", 5672)); // 创建一个信道 amqp::channel channel(&connection); // 声明队列 channel.declareQueue("model_1", AMQP::durable); // 绑定队列到默认交换机上 channel.bindQueue("", "model_1", "model_1"); // 创建一个消费者对象 auto consumer = channel.consume("model_1", AMQP::noack); // 监听队列 for (;;) { // 等待消息到达 auto message = consumer->pop(); // 打印消息内容 cout << "Received message: " << message->message() << endl; // 手动确认消息 channel.ack(message); } return 0; } ``` 在这个示例代码中,我们首先创建一个事件循环对象,然后创建一个TCP连接对象并连接到RabbitMQ服务器。接着,我们创建一个信道并声明一个名为“model_1”的队列,并将其绑定到默认交换机上。然后,我们创建一个消费者对象并使用“consume”方法开始监听队列。最后,我们使用一个无限循环来等待消息到达,并在收到消息后手动确认消息。 需要注意的是,在RabbitMQ中,消费者默认是自动确认消息的。如果你想手动确认消息,需要在消费者创建时指定“noack”选项,并在消息处理完毕后调用“channel.ack”方法来手动确认消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值