在发送和接收消息重要的类有: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中)

  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 连接启动

  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

RabbitMQ学习之ConntectionFactory与Conntection的认知的更多相关文章

  1. RabbitMQ学习系列(四): 几种Exchange 模式

    上一篇,讲了RabbitMQ的具体用法,可以看看这篇文章:RabbitMQ学习系列(三): C# 如何使用 RabbitMQ.今天说些理论的东西,Exchange 的几种模式. AMQP协议中的核心思 ...

  2. RabbitMQ学习系列(三): C# 如何使用 RabbitMQ

    上一篇已经讲了Rabbitmq如何在Windows平台安装,还不了解如何安装的朋友,请看我前面几篇文章:RabbitMQ学习系列一:windows下安装RabbitMQ服务 , 今天就来聊聊 C# 实 ...

  3. RabbitMQ学习总结 第三篇:工作队列Work Queue

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

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

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

  5. RabbitMQ学习总结 第二篇:快速入门HelloWorld

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

  6. RabbitMQ学习总结 第四篇:发布/订阅 Publish/Subscribe

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

  7. RabbitMQ学习总结 第五篇:路由Routing

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

  8. RabbitMQ学习总结 第六篇:Topic类型的exchange

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

  9. 人工智能范畴及深度学习主流框架,IBM Watson认知计算领域IntelligentBehavior介绍

    人工智能范畴及深度学习主流框架,IBM Watson认知计算领域IntelligentBehavior介绍 工业机器人,家用机器人这些只是人工智能的一个细分应用而已.图像识别,语音识别,推荐算法,NL ...

随机推荐

  1. VMware无法安装故障总结

    暂时遇到如下问题,并按此步骤可以解决,后续如有其它相关问题将继续更新: 1.无法获得 VMCI 驱动程序的版本: 句柄无效.如下图: 找到.vmx后缀配置文件 将如下白标""TRU ...

  2. 08.Web服务器-3.Web静态服务器

    1.显示固定的页面 from socket import * from multiprocessing import * import os def handleClient(clientSocket ...

  3. (16)Spring Boot使用Druid(编程注入)【从零开始学Spring Boot】

    在上一节使用是配置文件的方式进行使用druid,这里在扩散下使用编程式进行使用Druid,在上一节我们新建了一个类:DruidConfiguration我在这个类进行编码: package com.k ...

  4. 0619数据库_MySQL_由浅入深理解索引的实现

    转自http://blog.csdn.net/u010003835/article/details/51563348 这篇文章是介绍MySQL数据库中的索引是如何根据需求一步步演变最终成为B+树结构的 ...

  5. C#--async-await的用法

    NET 中的 async/await 异步编程 MSDN上的文章 **async与await最佳实践 需要先理解thread的用法,再掌握task的用法,才能力理解async和await的用法 usi ...

  6. 关于git修改和查看用户名邮箱

    git 查看/修改用户名.密码 查看用户名和邮箱地址: $ git config user.name $ git config user.email 修改用户名和邮箱地址: $ git config ...

  7. Mycat连接数据库之后导致表名全小写的问题分析研究

    初步研究:通过部署发现在Mycat中部署逻辑表表名大小写混合时,在Mycat连接后出现全变小.容易造成错误逻辑表(按混合表名创建物理表): 可能拯救的方法: 1.Linux下部署安装MySQL,默认不 ...

  8. linux c 操作utmp 和 wtmp 文件接口

    /var/run/utmp 保存当前在本系统中的用户信息 /var/log/wtmp 保存登陆过本系统的用户信息 他们保存的信息是基于结构体 struct utmp 的(/usr/include/bi ...

  9. 'hibernate.dialect' must be set when no Connection available

    今天碰到的这个问题,非常无厘头.网上搜索了非常多.都不靠谱,还是靠自己 解决方法是在hibernate.cfg.xml中加入 <property name="dialect" ...

  10. 热修复JSPatch之实战教程

      接上篇<热修复JSPatch之接口设计>,在这篇文章主要给大家讲述一下怎样高速具备热修复能力,当然了假设有人有志于把JSPatch系统的学习,甚至用JSPatch进行开发的.就没有必要 ...