在发送和接收消息重要的类有: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. UDP、线程、mutex锁(day15)

    一.基于UDP的网络编程模型 服务器端 .创建socket. .将fd和服务器的ip地址和端口号绑定 .recvfrom阻塞等待接收客户端数据 .业务处理 .响应客户端 客户端: .创建socket ...

  2. 洛谷P1090 合并果子【贪心】

    在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆.多多决定把所有的果子合成一堆. 每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和.可以看出,所 ...

  3. opencv(一)下载安装

    1.visual studio 工具---Nugget包管理器---管理解决方案的Nugget程序包 搜索opencv,点击安装 下载地址: 1.http://opencv.org/ 2.https: ...

  4. font-size:0消除元素间距

    容易发现,inline-block元素之间会有间距, <!DOCTYPE html> <html> <head> <title></title&g ...

  5. 【1】Django概述

    道生一,一生二,二生三,三生万物 无名天地之始,有名万物之母 ——老子 python程序web项目开发,是非常重要的一部分,Python为基础的web项目开发的框架有很多,django无疑是最强大we ...

  6. AtCoder ABC 076D - AtCoder Express

    传送门:http://abc076.contest.atcoder.jp/tasks/abc076_d 本题是一个运动学问题——匀变速运动. 一个质点,从静止开始运动.按照速度限制,可将运动划分成n个 ...

  7. JavaScript 事件代理绑定

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. gcc指定头文件路径及动态链接库路径

    gcc指定头文件路径及动态链接库路径   本文详细介绍了linux 下gcc头文件指定方法,以及搜索路径顺序的问题.另外,还总结了,gcc动态链接的方法以及路径指定,同样也讨论了搜索路径的顺序问题.本 ...

  9. Struts2 动态结果集

    1.index.jsp <body> 动态结果 一定不要忘了为动态结果的保存值设置set get方法 <ol> <li><a href="user/ ...

  10. iOS开发-自己定义重用机制给ScrollerView加入子视图

    事实上这个问题我非常早就想过,仅仅是没有通过去写程序实现,昨天有人提起,我就巧了一下 不知道大家打印郭tableview:cellforrow中cell初始的次数,也就是重用池中的cell个数.这个是 ...