Connection
连接,与rabbitmq server建立的一个连接,由ConnectionFactory创建,虽然创建时指定 了多个server address,但每个connection只与一个物理的server进行连接,此连接是基于Socket进行连接的,这个可以相似的理解为像一个DB Connection。
Channel
建立在connection基础上的一个通道,相对于connection来说,它是轻量级的。可以这样理解,它就像是hibernate里面的session一样,相对于DB Connection来说,session就是一个轻量级的东西。
Channel channel = conn.createChannel();
注:尽量避免在多线程中使用一个channel,Channel javadoc有如下说明:
While a Channel can be used by multiple threads, it‘s important to ensure that only one thread executes a command at once. Concurrent execution of commands will likely cause an UnexpectedFrameError to be thrown.
另官方Java Client API Guide里面也同样提到
Channel thread-safety
In general, Channel instances should not be used by more than one thread simultaneously: application code should maintain a clear notion of thread ownership for Channel instances. If more than one thread needs to access a particular Channel instance, the application should enforce mutual exclusion itself, for example by synchronising on the Channel.
Symptoms of incorrect serialisation of Channel operations include, but are not limited to, de>IllegalStateExceptionde>s with the message "cannot execute more than one synchronous AMQP command at a time", and de>UnexpectedFrameErrorde>s.
参考文章如下:
由于客户端需要从服务器获取方法,所以它需要在其生存期内一直保持连接的开放状态。这意味着连接可能会持续较长时间;几小时,几天或者几周。不管对客户端还是服务器来说,保持这些连接是很耗费资源的。为了在不使用大量的物理TCP/IP连接的情况下就能拥有大量的逻辑连接,AMQP使用了‘通道(channel)’ 的概念(在其Java and .NET客户端的IModel接口中有较为模糊的描述)。你可以在单个连接中创建多个channel,相对来说创建和销毁它们的代价要小的多。
在storm的spout中,要特别注意创建channel,不要乱用!
参考文章如下: