在发送和接收消息重要的类有:ConnectionFactory, Connection,Channel和 QueueingConsumer。

ConntectionFactory类是方便创建与AMQP代理相关联的Connection;下面来看看ConntectionFactory是如何创建一个Contention.首先通过new ConnectionFactory()创建一个ConnectionFactory;并设置此连接工厂的主机设置为broke IP。通过ConnectionFactory的newConnection()方法 创建一个Connection; newConnection方法通过得到当前连接的地址及端口号来获得一个Address,通过createFrameHandler的方法 来得到FrameHandler;再通过new AMQConnection(this, frameHandler)来得到Connection并启动。
    代码清单1创建Connection的源码(ConnectionFactory.Java中)

[java] view plaincopy print?
  1. protected FrameHandler createFrameHandler(Address addr)
  2. throws IOException {
  3. String hostName = addr.getHost();//获取主机IP
  4. int portNumber = portOrDefault(addr.getPort());//获取端口
  5. Socket socket = null;
  6. try {
  7. socket = factory.createSocket();
  8. configureSocket(socket);
  9. socket.connect(new InetSocketAddress(hostName, portNumber),
  10. connectionTimeout);
  11. return createFrameHandler(socket);
  12. } catch (IOException ioe) {
  13. quietTrySocketClose(socket);
  14. throw ioe;
  15. }
  16. }
  17. private static void quietTrySocketClose(Socket socket) {
  18. if (socket != null)
  19. try { socket.close(); } catch (Exception _) {/*ignore exceptions*/}
  20. }
  21. protected FrameHandler createFrameHandler(Socket sock)
  22. throws IOException
  23. {
  24. return new SocketFrameHandler(sock);
  25. }
  26. /**
  27. *  Provides a hook to insert custom configuration of the sockets
  28. *  used to connect to an AMQP server before they connect.
  29. *
  30. *  The default behaviour of this method is to disable Nagle's
  31. *  algorithm to get more consistently low latency.  However it
  32. *  may be overridden freely and there is no requirement to retain
  33. *  this behaviour.
  34. *
  35. *  @param socket The socket that is to be used for the Connection
  36. */
  37. protected void configureSocket(Socket socket) throws IOException{
  38. // disable Nagle's algorithm, for more consistently low latency
  39. socket.setTcpNoDelay(true);
  40. }
  41. /**
  42. * Create a new broker connection
  43. * @param addrs an array of known broker addresses (hostname/port pairs) to try in order
  44. * @return an interface to the connection
  45. * @throws IOException if it encounters a problem
  46. */
  47. public Connection newConnection(Address[] addrs) throws IOException {
  48. return newConnection(null, addrs);
  49. }
  50. /**
  51. * Create a new broker connection
  52. * @param executor thread execution service for consumers on the connection
  53. * @param addrs an array of known broker addresses (hostname/port pairs) to try in order
  54. * @return an interface to the connection
  55. * @throws IOException if it encounters a problem
  56. */
  57. public Connection newConnection(ExecutorService executor, Address[] addrs)
  58. throws IOException
  59. {
  60. IOException lastException = null;
  61. for (Address addr : addrs) {
  62. try {
  63. FrameHandler frameHandler = createFrameHandler(addr);
  64. AMQConnection conn =
  65. new AMQConnection(username,
  66. password,
  67. frameHandler,
  68. executor,
  69. virtualHost,
  70. getClientProperties(),
  71. requestedFrameMax,
  72. requestedChannelMax,
  73. requestedHeartbeat,
  74. saslConfig);
  75. conn.start();
  76. return conn;
  77. } catch (IOException e) {
  78. lastException = e;
  79. }
  80. }
  81. throw (lastException != null) ? lastException
  82. : new IOException("failed to connect");
  83. }
  84. /**
  85. * Create a new broker connection
  86. * @return an interface to the connection
  87. * @throws IOException if it encounters a problem
  88. */
  89. public Connection newConnection() throws IOException {
  90. return newConnection(null,
  91. new Address[] {new Address(getHost(), getPort())}
  92. );
  93. }
  94. /**
  95. * Create a new broker connection
  96. * @param executor thread execution service for consumers on the connection
  97. * @return an interface to the connection
  98. * @throws IOException if it encounters a problem
  99. */
  100. public Connection newConnection(ExecutorService executor) throws IOException {
  101. return newConnection(executor,
  102. new Address[] {new Address(getHost(), getPort())}
  103. );
  104. }

代码清单2 连接启动

[java] view plaincopy print?
  1. /**
  2. * Start up the connection, including the MainLoop thread.
  3. * Sends the protocol
  4. * version negotiation header, and runs through
  5. * Connection.Start/.StartOk, Connection.Tune/.TuneOk, and then
  6. * calls Connection.Open and waits for the OpenOk. Sets heart-beat
  7. * and frame max values after tuning has taken place.
  8. * @throws IOException if an error is encountered
  9. * either before, or during, protocol negotiation;
  10. * sub-classes {@link ProtocolVersionMismatchException} and
  11. * {@link PossibleAuthenticationFailureException} will be thrown in the
  12. * corresponding circumstances. If an exception is thrown, connection
  13. * resources allocated can all be garbage collected when the connection
  14. * object is no longer referenced.
  15. */
  16. public void start()
  17. throws IOException
  18. {
  19. this._running = true;
  20. // Make sure that the first thing we do is to send the header,
  21. // which should cause any socket errors to show up for us, rather
  22. // than risking them pop out in the MainLoop
  23. AMQChannel.SimpleBlockingRpcContinuation connStartBlocker =
  24. new AMQChannel.SimpleBlockingRpcContinuation();
  25. // We enqueue an RPC continuation here without sending an RPC
  26. // request, since the protocol specifies that after sending
  27. // the version negotiation header, the client (connection
  28. // initiator) is to wait for a connection.start method to
  29. // arrive.
  30. _channel0.enqueueRpc(connStartBlocker);
  31. try {
  32. // The following two lines are akin to AMQChannel's
  33. // transmit() method for this pseudo-RPC.
  34. _frameHandler.setTimeout(HANDSHAKE_TIMEOUT);
  35. _frameHandler.sendHeader();
  36. } catch (IOException ioe) {
  37. _frameHandler.close();
  38. throw ioe;
  39. }
  40. // start the main loop going
  41. new MainLoop("AMQP Connection " + getHostAddress() + ":" + getPort()).start();
  42. // after this point clear-up of MainLoop is triggered by closing the frameHandler.
  43. AMQP.Connection.Start connStart = null;
  44. AMQP.Connection.Tune connTune = null;
  45. try {
  46. connStart =
  47. (AMQP.Connection.Start) connStartBlocker.getReply().getMethod();
  48. _serverProperties = Collections.unmodifiableMap(connStart.getServerProperties());
  49. Version serverVersion =
  50. new Version(connStart.getVersionMajor(),
  51. connStart.getVersionMinor());
  52. if (!Version.checkVersion(clientVersion, serverVersion)) {
  53. throw new ProtocolVersionMismatchException(clientVersion,
  54. serverVersion);
  55. }
  56. String[] mechanisms = connStart.getMechanisms().toString().split(" ");
  57. SaslMechanism sm = this.saslConfig.getSaslMechanism(mechanisms);
  58. if (sm == null) {
  59. throw new IOException("No compatible authentication mechanism found - " +
  60. "server offered [" + connStart.getMechanisms() + "]");
  61. }
  62. LongString challenge = null;
  63. LongString response = sm.handleChallenge(null, this.username, this.password);
  64. do {
  65. Method method = (challenge == null)
  66. ? new AMQP.Connection.StartOk.Builder()
  67. .clientProperties(_clientProperties)
  68. .mechanism(sm.getName())
  69. .response(response)
  70. .build()
  71. : new AMQP.Connection.SecureOk.Builder().response(response).build();
  72. try {
  73. Method serverResponse = _channel0.rpc(method).getMethod();
  74. if (serverResponse instanceof AMQP.Connection.Tune) {
  75. connTune = (AMQP.Connection.Tune) serverResponse;
  76. } else {
  77. challenge = ((AMQP.Connection.Secure) serverResponse).getChallenge();
  78. response = sm.handleChallenge(challenge, this.username, this.password);
  79. }
  80. } catch (ShutdownSignalException e) {
  81. throw new PossibleAuthenticationFailureException(e);
  82. }
  83. } while (connTune == null);
  84. } catch (ShutdownSignalException sse) {
  85. _frameHandler.close();
  86. throw AMQChannel.wrap(sse);
  87. } catch(IOException ioe) {
  88. _frameHandler.close();
  89. throw ioe;
  90. }
  91. try {
  92. int channelMax =
  93. negotiatedMaxValue(this.requestedChannelMax,
  94. connTune.getChannelMax());
  95. _channelManager = new ChannelManager(this._workService, channelMax);
  96. int frameMax =
  97. negotiatedMaxValue(this.requestedFrameMax,
  98. connTune.getFrameMax());
  99. this._frameMax = frameMax;
  100. int heartbeat =
  101. negotiatedMaxValue(this.requestedHeartbeat,
  102. connTune.getHeartbeat());
  103. setHeartbeat(heartbeat);
  104. _channel0.transmit(new AMQP.Connection.TuneOk.Builder()
  105. .channelMax(channelMax)
  106. .frameMax(frameMax)
  107. .heartbeat(heartbeat)
  108. .build());
  109. _channel0.exnWrappingRpc(new AMQP.Connection.Open.Builder()
  110. .virtualHost(_virtualHost)
  111. .build());
  112. } catch (IOException ioe) {
  113. _heartbeatSender.shutdown();
  114. _frameHandler.close();
  115. throw ioe;
  116. } catch (ShutdownSignalException sse) {
  117. _heartbeatSender.shutdown();
  118. _frameHandler.close();
  119. throw AMQChannel.wrap(sse);
  120. }
  121. // We can now respond to errors having finished tailoring the connection
  122. this._inConnectionNegotiation = false;
  123. return;
  124. }

转载:http://wubin850219.iteye.com/blog/1007984

转载于:https://www.cnblogs.com/telwanggs/p/7124719.html

RabbitMQ学习之ConntectionFactory与Conntection的认知相关推荐

  1. RabbitMQ学习系列二:.net 环境下 C#代码使用 RabbitMQ 消息队列

    上一篇已经讲了Rabbitmq如何在Windows平台安装,不懂请移步:RabbitMQ学习系列一:windows下安装RabbitMQ服务 一.理论: .net环境下,C#代码调用RabbitMQ消 ...

  2. RabbitMQ学习总结 第一篇:理论篇

    目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...

  3. RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决)

    RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决) 参考文章: (1)RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决) (2)https://www.cnblogs. ...

  4. rabbitmq 学习-9- RpcClient发送消息和同步接收消息原理

    rabbitmq 学习-9- RpcClient发送消息和同步接收消息原理

  5. RabbitMQ学习之集群消息可靠性测试

    之前介绍过关于消息发送和接收的可靠性:RabbitMQ学习之消息可靠性及特性  下面主要介绍一下集群环境下,rabbitmq实例宕机的情况下,消息的可靠性.验证rabbitmq版本[3.4.1].  ...

  6. 官网英文版学习——RabbitMQ学习笔记(二)RabbitMQ安装

    一.安装RabbitMQ的依赖Erlang 要进行RabbitMQ学习,首先需要进行RabbitMQ服务的安装,安装我们可以根据官网指导进行http://www.rabbitmq.com/downlo ...

  7. RabbitMQ学习笔记(3)----RabbitMQ Worker的使用

    1. Woker队列结构图 这里表示一个生产者生产了消息发送到队列中,但是确有两个消费者在消费同一个队列中的消息. 2. 创建一个生产者 Producer如下: package com.wangx.r ...

  8. RabbitMQ学习

    RabbitMQ学习 1.概述 用于进程通信的中间件. 优势: 劣势: 1.应用解耦:提高了系统容错性和可维护性 1.系统依赖越多不能保证MQ的高可用 2.异步提速:提升用户体验和系统吞吐量 2.复杂 ...

  9. RabbitMQ 学习笔记

    RabbitMQ 学习笔记 RabbitMQ 学习笔记 1. 中间件 1.1 什么是中间件 1.2 为什么要使用消息中间件 1.3 中间件特点 1.4 在项目中什么时候使用中间件技术 2. 中间件技术 ...

最新文章

  1. 【Android TV 开发】焦点处理 ( 父容器与子组件焦点获取关系处理 | 不同电视设备上的兼容问题 | 触摸获取焦点 | 按键获取焦点 )
  2. python抢票代码_教你用Python动刷新抢12306火车票,附源码!
  3. python创建多个txt文件-python-在目录中创建多个文本文件的字数字...
  4. chrome session丢失_一文带你彻底读懂Cookie、Session、Token到底是什么
  5. SAP 电商云 Spartacus UI B2B checkout 点击 Continue 不能跳转到下一页面
  6. 联合体(union)和结构体(struct)的区别
  7. Multisim破解教程
  8. 苹果8a1660是什么版本_苹果a1780是什么版本
  9. 【电路设计】尖峰电压与浪涌电流
  10. 关于计算机知识的动画电影,动画概论总复习题目(附答案)
  11. 前端开发公众号的调试
  12. 基于51单片机智能电子密码锁的设计
  13. python人脸识别opencv_python中使用Opencv进行人脸识别
  14. js如何转换json字符串,js如何转换为数值型
  15. Hexo个人博客NexT主题添加Local Search本地搜索
  16. 打开i信服务器正在运行中,【网络异常,0/12157 Unknown】i信登录时出现
  17. 吴军:AI应该变成通识教育,区块链不是炒概念
  18. LNMP架构部署及应用
  19. 日语能力考N1复习1
  20. 帧同步游戏 服务器相关实现

热门文章

  1. nginx简介--理解nginx配置/模块/openresty
  2. (32)FPGA面试技能提升篇(EMMC)
  3. (12)verilog语言编写8路选择器
  4. linux下dds软件,【数据库】Linux 单实例环境下实现Oracle数据库和DDS软件的开机自动重启...
  5. QT5日志功能(qDebug、qWarnng、qCritical、qFatal)
  6. python读取多行json_如何在Python中读取包含多个JSON对象的JSON文件?
  7. 【蓝桥杯单片机】IIC通讯协议与EEPROM(AT24C02)(官方驱动源码改写)
  8. 【STM32】【STM32CubeMX】STM32CubeMX的使用之七:定时器输入捕获实现超声波测距
  9. Linux下pthread的读写锁的优先级问题
  10. 【MyBatis-Plus】第一章 快速入门