在发送和接收消息重要的类有: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. vue-router 懒加载

    懒加载:也叫延迟加载,即在需要的时候进行加载,按需加载. 那vue 为什么需要懒加载呢? 使用 vue-cli构建的项目,在默认情况下,执行 npm run build  会将所有的 js代码打包为一 ...

  2. 51nod1079 中国剩余定理【数论】

    一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K.例如,K % 2 = 1, K % 3 = 2, K % 5 = 3.符合条件的最小的K = 23. Input 第1行:1个数N表 ...

  3. [BZOJ5072] 小A的树

    设计状态\(f[i][j]\)表示以i为根的子树,包含j个点的最小黑点数,\(g[i][j]\)表示以\(i\) 为子树,包含\(j\)个点的最大黑点数,然后树形背包转移即可. 每次询问的时候就看包含 ...

  4. 解决HTML select控件 设置属性 disabled 后无法向后台传值的方法

    大家都知道有时候修改数据的时候我们希望有一些数据是不可以修改的,通常情况下我们会将input框设置为 readonly , 但是 select 控件没有这个属性,需要使用另一个属性 disabled ...

  5. Vue packages version mismatch

    开发过程中,之前做的vue项目,一段时间后拿出来重新运行,报错: 打开vue-template-compiler/index.js查看错误提示,如下: 当安装的vue版本和package.json中的 ...

  6. android的数据与访问(2)-delphi xe7如何存取我的app配置参数文件?

    这种方法不推荐,因为该SharedPreference是android的方法.你想跨平台,在ios上就不能使用.建议还是用ini or xml.android因为读写该二种文件比较繁琐,所以推出自己简 ...

  7. MySQL日志格式 binlog_format

    MySQL 5.5 中对于二进制日志 (binlog) 有 3 种不同的格式可选:Mixed,Statement,Row,默认格式是 Statement.总结一下这三种格式日志的优缺点. MySQL ...

  8. MySQL特异功能之:Impossible WHERE noticed after reading const tables

    用EXPLAIN看MySQL的执行计划时经常会看到Impossible WHERE noticed after reading const tables这句话,意思是说MySQL通过读取"c ...

  9. 楼控-西门子insight BBMD设置

    BBMD设置的目的就是让两个不同网段的设备可以同时在一个系统中访问的操作. 比如你有两个bacnet的网络,但是一个是192.168.0.1-192.168.0.255的网段,另一个是10.0.0.1 ...

  10. [bzoj1552\bzoj2506][Cqoi2014]robotic sort 排序机械臂_非旋转Treap

    robotic sort 排序机械臂 bzoj-1552 bzoj-2506 Cqoi-2014 题目大意:给定一个序列,让你从1到n,每次将[1,p[i]]这段区间反转,p[i]表示整个物品权值第i ...