RabbitMQ学习之ConntectionFactory与Conntection的认知
在发送和接收消息重要的类有: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中)
- protected FrameHandler createFrameHandler(Address addr)
- throws IOException {
- String hostName = addr.getHost();//获取主机IP
- int portNumber = portOrDefault(addr.getPort());//获取端口
- Socket socket = null;
- try {
- socket = factory.createSocket();
- configureSocket(socket);
- socket.connect(new InetSocketAddress(hostName, portNumber),
- connectionTimeout);
- return createFrameHandler(socket);
- } catch (IOException ioe) {
- quietTrySocketClose(socket);
- throw ioe;
- }
- }
- private static void quietTrySocketClose(Socket socket) {
- if (socket != null)
- try { socket.close(); } catch (Exception _) {/*ignore exceptions*/}
- }
- protected FrameHandler createFrameHandler(Socket sock)
- throws IOException
- {
- return new SocketFrameHandler(sock);
- }
- /**
- * Provides a hook to insert custom configuration of the sockets
- * used to connect to an AMQP server before they connect.
- *
- * The default behaviour of this method is to disable Nagle's
- * algorithm to get more consistently low latency. However it
- * may be overridden freely and there is no requirement to retain
- * this behaviour.
- *
- * @param socket The socket that is to be used for the Connection
- */
- protected void configureSocket(Socket socket) throws IOException{
- // disable Nagle's algorithm, for more consistently low latency
- socket.setTcpNoDelay(true);
- }
- /**
- * Create a new broker connection
- * @param addrs an array of known broker addresses (hostname/port pairs) to try in order
- * @return an interface to the connection
- * @throws IOException if it encounters a problem
- */
- public Connection newConnection(Address[] addrs) throws IOException {
- return newConnection(null, addrs);
- }
- /**
- * Create a new broker connection
- * @param executor thread execution service for consumers on the connection
- * @param addrs an array of known broker addresses (hostname/port pairs) to try in order
- * @return an interface to the connection
- * @throws IOException if it encounters a problem
- */
- public Connection newConnection(ExecutorService executor, Address[] addrs)
- throws IOException
- {
- IOException lastException = null;
- for (Address addr : addrs) {
- try {
- FrameHandler frameHandler = createFrameHandler(addr);
- AMQConnection conn =
- new AMQConnection(username,
- password,
- frameHandler,
- executor,
- virtualHost,
- getClientProperties(),
- requestedFrameMax,
- requestedChannelMax,
- requestedHeartbeat,
- saslConfig);
- conn.start();
- return conn;
- } catch (IOException e) {
- lastException = e;
- }
- }
- throw (lastException != null) ? lastException
- : new IOException("failed to connect");
- }
- /**
- * Create a new broker connection
- * @return an interface to the connection
- * @throws IOException if it encounters a problem
- */
- public Connection newConnection() throws IOException {
- return newConnection(null,
- new Address[] {new Address(getHost(), getPort())}
- );
- }
- /**
- * Create a new broker connection
- * @param executor thread execution service for consumers on the connection
- * @return an interface to the connection
- * @throws IOException if it encounters a problem
- */
- public Connection newConnection(ExecutorService executor) throws IOException {
- return newConnection(executor,
- new Address[] {new Address(getHost(), getPort())}
- );
- }
代码清单2 连接启动
- /**
- * Start up the connection, including the MainLoop thread.
- * Sends the protocol
- * version negotiation header, and runs through
- * Connection.Start/.StartOk, Connection.Tune/.TuneOk, and then
- * calls Connection.Open and waits for the OpenOk. Sets heart-beat
- * and frame max values after tuning has taken place.
- * @throws IOException if an error is encountered
- * either before, or during, protocol negotiation;
- * sub-classes {@link ProtocolVersionMismatchException} and
- * {@link PossibleAuthenticationFailureException} will be thrown in the
- * corresponding circumstances. If an exception is thrown, connection
- * resources allocated can all be garbage collected when the connection
- * object is no longer referenced.
- */
- public void start()
- throws IOException
- {
- this._running = true;
- // Make sure that the first thing we do is to send the header,
- // which should cause any socket errors to show up for us, rather
- // than risking them pop out in the MainLoop
- AMQChannel.SimpleBlockingRpcContinuation connStartBlocker =
- new AMQChannel.SimpleBlockingRpcContinuation();
- // We enqueue an RPC continuation here without sending an RPC
- // request, since the protocol specifies that after sending
- // the version negotiation header, the client (connection
- // initiator) is to wait for a connection.start method to
- // arrive.
- _channel0.enqueueRpc(connStartBlocker);
- try {
- // The following two lines are akin to AMQChannel's
- // transmit() method for this pseudo-RPC.
- _frameHandler.setTimeout(HANDSHAKE_TIMEOUT);
- _frameHandler.sendHeader();
- } catch (IOException ioe) {
- _frameHandler.close();
- throw ioe;
- }
- // start the main loop going
- new MainLoop("AMQP Connection " + getHostAddress() + ":" + getPort()).start();
- // after this point clear-up of MainLoop is triggered by closing the frameHandler.
- AMQP.Connection.Start connStart = null;
- AMQP.Connection.Tune connTune = null;
- try {
- connStart =
- (AMQP.Connection.Start) connStartBlocker.getReply().getMethod();
- _serverProperties = Collections.unmodifiableMap(connStart.getServerProperties());
- Version serverVersion =
- new Version(connStart.getVersionMajor(),
- connStart.getVersionMinor());
- if (!Version.checkVersion(clientVersion, serverVersion)) {
- throw new ProtocolVersionMismatchException(clientVersion,
- serverVersion);
- }
- String[] mechanisms = connStart.getMechanisms().toString().split(" ");
- SaslMechanism sm = this.saslConfig.getSaslMechanism(mechanisms);
- if (sm == null) {
- throw new IOException("No compatible authentication mechanism found - " +
- "server offered [" + connStart.getMechanisms() + "]");
- }
- LongString challenge = null;
- LongString response = sm.handleChallenge(null, this.username, this.password);
- do {
- Method method = (challenge == null)
- ? new AMQP.Connection.StartOk.Builder()
- .clientProperties(_clientProperties)
- .mechanism(sm.getName())
- .response(response)
- .build()
- : new AMQP.Connection.SecureOk.Builder().response(response).build();
- try {
- Method serverResponse = _channel0.rpc(method).getMethod();
- if (serverResponse instanceof AMQP.Connection.Tune) {
- connTune = (AMQP.Connection.Tune) serverResponse;
- } else {
- challenge = ((AMQP.Connection.Secure) serverResponse).getChallenge();
- response = sm.handleChallenge(challenge, this.username, this.password);
- }
- } catch (ShutdownSignalException e) {
- throw new PossibleAuthenticationFailureException(e);
- }
- } while (connTune == null);
- } catch (ShutdownSignalException sse) {
- _frameHandler.close();
- throw AMQChannel.wrap(sse);
- } catch(IOException ioe) {
- _frameHandler.close();
- throw ioe;
- }
- try {
- int channelMax =
- negotiatedMaxValue(this.requestedChannelMax,
- connTune.getChannelMax());
- _channelManager = new ChannelManager(this._workService, channelMax);
- int frameMax =
- negotiatedMaxValue(this.requestedFrameMax,
- connTune.getFrameMax());
- this._frameMax = frameMax;
- int heartbeat =
- negotiatedMaxValue(this.requestedHeartbeat,
- connTune.getHeartbeat());
- setHeartbeat(heartbeat);
- _channel0.transmit(new AMQP.Connection.TuneOk.Builder()
- .channelMax(channelMax)
- .frameMax(frameMax)
- .heartbeat(heartbeat)
- .build());
- _channel0.exnWrappingRpc(new AMQP.Connection.Open.Builder()
- .virtualHost(_virtualHost)
- .build());
- } catch (IOException ioe) {
- _heartbeatSender.shutdown();
- _frameHandler.close();
- throw ioe;
- } catch (ShutdownSignalException sse) {
- _heartbeatSender.shutdown();
- _frameHandler.close();
- throw AMQChannel.wrap(sse);
- }
- // We can now respond to errors having finished tailoring the connection
- this._inConnectionNegotiation = false;
- return;
- }
转载:http://wubin850219.iteye.com/blog/1007984
RabbitMQ学习之ConntectionFactory与Conntection的认知的更多相关文章
- RabbitMQ学习系列(四): 几种Exchange 模式
上一篇,讲了RabbitMQ的具体用法,可以看看这篇文章:RabbitMQ学习系列(三): C# 如何使用 RabbitMQ.今天说些理论的东西,Exchange 的几种模式. AMQP协议中的核心思 ...
- RabbitMQ学习系列(三): C# 如何使用 RabbitMQ
上一篇已经讲了Rabbitmq如何在Windows平台安装,还不了解如何安装的朋友,请看我前面几篇文章:RabbitMQ学习系列一:windows下安装RabbitMQ服务 , 今天就来聊聊 C# 实 ...
- RabbitMQ学习总结 第三篇:工作队列Work Queue
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...
- RabbitMQ学习总结 第一篇:理论篇
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...
- RabbitMQ学习总结 第二篇:快速入门HelloWorld
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...
- RabbitMQ学习总结 第四篇:发布/订阅 Publish/Subscribe
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...
- RabbitMQ学习总结 第五篇:路由Routing
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...
- RabbitMQ学习总结 第六篇:Topic类型的exchange
目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...
- 人工智能范畴及深度学习主流框架,IBM Watson认知计算领域IntelligentBehavior介绍
人工智能范畴及深度学习主流框架,IBM Watson认知计算领域IntelligentBehavior介绍 工业机器人,家用机器人这些只是人工智能的一个细分应用而已.图像识别,语音识别,推荐算法,NL ...
随机推荐
- 继续聊WPF——为ListView的行设置样式
<Window x:Class="Wpf_GridHeaderStyle_sample.Window1" xmlns="http://schemas.microso ...
- JUnit单元测试实践:测试工具类和方法(EmptyUtils)
以前的时候(读大学时),我认为写单元测试太费事了.现在,我改变看法了. 工作中,为了提高Web开发的质量和效率,近期又为了保证自己的工具类等一系列可复用组件的质量,我煞费苦心地开始认真学习和撰写单元测 ...
- Linux命令及全称(部分)
man: manual 意思是手册,可以用这个命令查询其他命令的用法. pwd:print working directory 显示当前工作路径. su:swith user 切换用户,切换 ...
- FreeMarker基本使用
FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写 l FreeMarker被设计用来生成HTML Web页面,特别是基于MVC模式的应用程序 ...
- orcale 日期显示格式化
SQL> select * 2 from emp 3 where hiredate='1987-11-17'; where hiredate='1987-11-17' * 第 3 行出现错误: ...
- Effective C++ Item 28 避免返回对象内部数据的引用或指针
本文为senlie原创.转载请保留此地址:http://blog.csdn.net/zhengsenlie Item 31 经验:避免返回handles(包含 references.指针.迭代器)指向 ...
- 时间格式字符串转化为date和时间戳
NSString *dateStr=@"2012-05-17 11:23:23"; NSLog(@"dateStr=%@",dateStr); NSDateFo ...
- find命令用法举例
显示7天前(后)的时间 for linux “find”的用法: 删除”/tmp”目录下,7天前的文件 find /tmp -name "*" -type f-mtime +7 - ...
- Grace Hopper
葛丽丝·穆雷·霍普(英语:Grace Murray Hopper,1906年12月9日-1992年1月1日),本姓穆雷(Murray),霍普(Hopper)为夫姓,生于美国纽约州纽约市,美国海军准将及 ...
- luogu1168 中位数
题目大意 给出一个长度为N的非负整数序列A[i],对于所有1 ≤ k ≤ (N + 1) / 2,输出A[1], A[3], -, A[2k - 1]的中位数.即前1,3,5,--个数的中位数. 题解 ...