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 ...
随机推荐
- vue-router 懒加载
懒加载:也叫延迟加载,即在需要的时候进行加载,按需加载. 那vue 为什么需要懒加载呢? 使用 vue-cli构建的项目,在默认情况下,执行 npm run build 会将所有的 js代码打包为一 ...
- 51nod1079 中国剩余定理【数论】
一个正整数K,给出K Mod 一些质数的结果,求符合条件的最小的K.例如,K % 2 = 1, K % 3 = 2, K % 5 = 3.符合条件的最小的K = 23. Input 第1行:1个数N表 ...
- [BZOJ5072] 小A的树
设计状态\(f[i][j]\)表示以i为根的子树,包含j个点的最小黑点数,\(g[i][j]\)表示以\(i\) 为子树,包含\(j\)个点的最大黑点数,然后树形背包转移即可. 每次询问的时候就看包含 ...
- 解决HTML select控件 设置属性 disabled 后无法向后台传值的方法
大家都知道有时候修改数据的时候我们希望有一些数据是不可以修改的,通常情况下我们会将input框设置为 readonly , 但是 select 控件没有这个属性,需要使用另一个属性 disabled ...
- Vue packages version mismatch
开发过程中,之前做的vue项目,一段时间后拿出来重新运行,报错: 打开vue-template-compiler/index.js查看错误提示,如下: 当安装的vue版本和package.json中的 ...
- android的数据与访问(2)-delphi xe7如何存取我的app配置参数文件?
这种方法不推荐,因为该SharedPreference是android的方法.你想跨平台,在ios上就不能使用.建议还是用ini or xml.android因为读写该二种文件比较繁琐,所以推出自己简 ...
- MySQL日志格式 binlog_format
MySQL 5.5 中对于二进制日志 (binlog) 有 3 种不同的格式可选:Mixed,Statement,Row,默认格式是 Statement.总结一下这三种格式日志的优缺点. MySQL ...
- MySQL特异功能之:Impossible WHERE noticed after reading const tables
用EXPLAIN看MySQL的执行计划时经常会看到Impossible WHERE noticed after reading const tables这句话,意思是说MySQL通过读取"c ...
- 楼控-西门子insight BBMD设置
BBMD设置的目的就是让两个不同网段的设备可以同时在一个系统中访问的操作. 比如你有两个bacnet的网络,但是一个是192.168.0.1-192.168.0.255的网段,另一个是10.0.0.1 ...
- [bzoj1552\bzoj2506][Cqoi2014]robotic sort 排序机械臂_非旋转Treap
robotic sort 排序机械臂 bzoj-1552 bzoj-2506 Cqoi-2014 题目大意:给定一个序列,让你从1到n,每次将[1,p[i]]这段区间反转,p[i]表示整个物品权值第i ...