当前位置: 首页 > ActiveMQ in Action 读书笔记 > 正文

12.5 使用 失效转移协议 应对代理或网络故障

12.5 Surviving network or broker failure with the failover protocol

12.5 使用 失效转移协议 应对代理或网络故障

We introduced the failover protocol in chapter 4, where we explained the basicsbehind allowing a client to fail over to another ActiveMQ broker in the case of failure.The failover protocol is the default protocol used by the Java client, so it’s worth lookingin more detail at some of its optional features and capabilities.  在第4章中.我们介了 失效转移协议 ,解释了在失效的情况下允许客户端转移到另外一个ActiveMQ代理的背后基础知识.失效转移协议是ActiveMQ代理的Java客户端使用的默认协议,因此我们有必要了解更多该协议相关的特性和功能.
By default, you specify in the client URI one or more ActiveMQ brokers that couldbe used for the connection: 默认情况下,你给客户端的URI指定了一个或者多个ActiveMQ代理以便用来创建连接:
failover:(tcp://host1:61616,tcp://host2:61616,ssl://host2:61616)
By the way, specifying the failover transport URI like this is okay, too, although it canget a bit messy if there are any embedded query parameters. 这种方式指定URL是没有问题的,但是假如有一些嵌入的查询参数的话这种方式指定的URI看起来有些混乱.
ActiveMQ will connect to one of the brokers defined in the list, selecting one atrandom. With the failover protocol, the ActiveMQ client will instantiate a periodickeepalive protocol, so that it can detect whether the broker is no longer reachable(connection or broker lost). When it detects that the broker is no longer available, itwill randomly select another broker from the list provided at startup. If only one brokerURI is provided, the client will periodically check to see if the broker is availableagain. It’s possible to listen for transport interrupts by setting a TransportListeneron the ActiveMQ connection: ActiveMQ将在指定的URI列表中随机选择一个然后创建到该代理的连接.通过使用失效转移协议,ActiveMQ客户端会定期启动一个保持连接协议,以便侦测代理是否不可达(连接丢失或代理丢失).如果侦测到代理不再可用,失效转移连接器会从提供的URI列表中随机的选择另一个代理的URI.如果仅提供了一个代理URI,客户端会隔一段时间后再检测这个唯一代理是否可用了.可以通过给ActiveMQ连接设置TransportListener来监听传输的是否中断了,如下代码所示:
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.transport.DefaultTransportListener;
...
ActiveMQConnection connection = (ActiveMQConnection)
connectionFactory.createConnection();
 
connection.addTransportListener(new DefaultTransportListener() 
{
  public void onException(IOException arg0) 
  {
    System.err.println("This is bad");
  }
   
  public void transportInterrupted() 
  {
    System.out.println("Transport interrupted");
  }
   
  public void transportResumed() 
  {
    System.out.println("Transport resumed");
  }
});
connection.start();
When you supply the failover protocol with more than one transport URI to use, bydefault it will select one at random to use, to ensure load balancing of clients acrossbrokers. When you want to have a guaranteed order of brokers that the client willconnect to, you need to disable the random selection of brokers by disabling therandomize failover property: 如果你为失效转移连接器提供了多个URI,那么默认情况下,连接器会随机使用其中的一个URI,以便保证客户端访问代理的负载均衡.当你需要确保客户端按照设定的顺序来连接指定的代理是,你要设置失效转移连接器的randomize属性为false以便关闭随机选择代理URI来连接的功能.
failover:(tcp://master:61616,tcp://slave:61616)?randomize=false
If none of the ActiveMQ brokers specified by the failover URI are available, then bydefault the failover transport will wait before trying again. The failover protocol willwait an increasing amount of time between each successive failure to connect to anActiveMQ broker—this is called an exponential back-off. The failover protocol by defaulthas useExponentialBackOff enabled. The wait time between successive attempts toconnect is called the initialReconnectDelay (initial value is 10ms) and the multiplierto increase the wait time is called the backOffMultiplier (default value is 2.0). 如果失效转移连接器中设定的URI都不可用,那么默认情况下,失效转移连接器会等待一段时间然后重新尝试连接.相邻两次失败后尝试重新连接之前的等待时间是递增的–这被称为指数级back-off.失效转移连接器默认会开启useExponentialBackOff.在重新尝试连接之前的等待时间称为initialReconnectDelay(初始值为10毫秒)下一次失败后尝试重新连接之前的等待时间与前一次等待时间的倍数称为backOffMultiplier(默认值为2.0).
You can also set the maximum time period for the failover protocol by using max-ReconnectDelay (default is 30000ms). An example configuration is shown next: 你也可以使用maxReconnectDelay(默认值为30000毫秒)设置失效后重新连接之前等待时长的最大值.下面是一个示例配置代码:
failover:(tcp://master:61616,tcp://slave:61616)?backOffMultiplier=1.5,initialReconnectDelay=1000
One potential problem that you may run into using any transport protocol based onTCP is the ability to know when a peer (for ActiveMQ, this will be the broker) has died.This can happen for several reasons, like the failure of the ActiveMQ broker or loss ofnetwork. 使用基于TCP的传输连接器可能导致一个潜在的问题,即,连接的对端(对于ActiveMQ来说,这个对端是指代理)是否已经失效了.导致这个问题的原因有几个,比如ActiveMQ代理失效或者网络连接丢失.
Also, if there’s a firewall between the ActiveMQ client and broker, it maydrop the connection if it’s inactive for some time. It’s possible to configure keepaliveon the TCP connection, but this is operating system–specific and can require changesto kernel parameters—and doesn’t work well in heterogeneous environments. Forthis reason, ActiveMQ uses a keepalive protocol on top of its transports, to keep firewallsopen and also detect whether the broker is no longer reachable. The keepaliveprotocol periodically sends a lightweight command message to the broker, andexpects a response. 另外,如果在ActiveMQ代理和客户端之间存在防火墙,如果连接长时间处于非活动状态,防火墙可能会切断连接.可以配置TCP连接的keepalive属性,但这个属性是操作系统属性,可能会导致修改系统内容参数并且在复杂环境中不能很好的工作.鉴于此,ActiveMQ在传输连接器的上层使用一个保持连接协议以保持防火墙始终打开同时监测代理是否不可达.keepalive协议每隔一段时间会发送一个轻量级的命令消息给代理然后等待代理的响应.
If it doesn’t receive one within a given time period, ActiveMQ willassume that the transport is no longer valid. The failover transport listens for failedtransports and will select another transport to use on such a failure. The parameterused by the keepalive protocol in ActiveMQ is maxInactivityDuration, which is anOpenWire property; the default is 30000 (milliseconds). You can specify a differenttimeout to be used with the failover transport, as shown: 如果没有在规定时间内收到响应,ActiveMQ会认为当前的传输连接器不再可用.失效转移连接器监听到失效的连接器后会选择另外一个连接器来应对前面连接器的失效.ActiveMQ在keepalive协议中使用maxInactivityDuration参数是一个OpenWire属性,默认值为30000(毫秒).你可以为失效转移协议的这个参数设置新值,如下代码所示:
failover:(tcp://host1:61616?wireFormat.maxInactivityDuration=1000,
tcp://host2:61616?wireFormat.maxInactivityDuration=1000)
Note that you have to set this parameter (and any other OpenWire properties) on thetransports used by the failover protocol, not the failover protocol itself. 注意,你必须为使用失效转移协议的连接器设置这个参数(以及其他所有的OpenWire属性),而不是为失效转移本身设置这个
By default, the delivery mode for sending messages from an ActiveMQ client is persistent(this is so ActiveMQ is compliant with the JMS specification). A message sentwith a persistent delivery mode will be synchronous—send() will block until it gets areceipt from the broker that it has successfully received and stored the message. Forapplications where performance is important, using nonpersistent delivery can dramaticallyimprove results (see chapter 13). When nonpersistent delivery is used, messagesare sent asynchronously, which has the downside that you can potentially losemessages in flight if a transport fails. You can configure the failover transport to preventthis by enabling message caching with the trackMessages failover transportproperty. You can also control the maximum size of this message cache by use of themaxCacheSize failover property—the default is 128 KB (the memory allocation sizeallowed for the message 默认情况下,ActiveMQ客户端在发送消息时使用的分发模式是持久化的(因此ActiveMQ是遵循JMS规范的).使用持久化分发模式的消息将使用同步方式发送,这种方式发送消息后,发送消息的线程将会阻塞直到收到代理的回执以确定消息成功发送以及成功存储了.对于关注性能的程序来说,使用非持久化分发方式能显著提高性能(参见13章).使用非你持久化分发时,消息都是异步发送,这样就产生了隐患–如果传输连接器失效你可能会丢失消息.你可以通过配置失效转移连接器的trackMessages属性来启用消息缓存以避免消息丢失.这种缓存消息的最大值也可以使用失效转移连接器的maxCacheSize配置–该配置的默认值是128KB(允许分配给消息缓存的内存大小).
Here’s an example configuration for enabling cachingand setting the maximum cache 下面是示例配置代码,配置中通过设置最大缓存大小启用了消息缓存:
failover:(tcp://host1:61616,tcp://host2:61616)?trackMessages=true,maxCacheSize=256000
For high-performance applications, fast failover is important too. It takes a considerableamount of time to build up a new transport connection (in the order of tens tohundreds of milliseconds), so to enable fast failover, ActiveMQ can optionally allowthe failover protocol to build a backup connection ready to go if the primary transportfails. The failover property to set to allow a backup connection is unsurprisinglycalled backup. You can have more than one backup enabled (the default is 1) by settingthe failover property backupPoolSize. 对于高性能程序来说,失效转移协议也是非常重要的.新建一个传输连接需要的时间是很可观的(需要几十到几百毫秒),因此启用了快速失效转移后,ActiveMQ能有选择性的运行失效转移协议创建一个备份连接,以便能在主连接失效时迅速接替主连接继续工作.设置运行失效转移连接器建立备份连接的属性毫无悬念的被称为backup.你可以通过backupPoolSize属性设置多于一个的备份(默认值是1
An example failover URI using backup is shown next: 启用备份连接的失效转移URI示例代码如下:
failover:(tcp://host1:61616,tcp://host2:61616,tcp://host3:61616)?backup=true,backupPoolSize=2
So far we’ve looked at configuring the failover transport with a static list ofURIs  to  the  broker, but  an  ActiveMQ  broker does  know  what  brokers it’sconnected to, so  it can optionally  dynamically update clients  with changes tothe cluster as brokers come and go.  To enable dynamic updates of brokers to  anActiveMQ client,  we need  to enable  the property  updateClusterClients on  theTransportConnector used in the ActiveMQ broker configuration. Properties on  theTransportConnector are used to control the updates; these are as shown in  table12.1. 到目前为止,我们都是使用一个静态的URI列表来配置失效转移连接器的,但是ActiveMQ是可以自行侦测需要连接的代理,因此ActiveMQ客户端可以在代理新增到集群或者从集群中移除时动态的更新代理集群.我们需要启用传输连接器的updateClusterClients属性来为ActiveMQ客户端启用动态更新代理集群.TransportConnector中用于控制代理集群自动更新的属性如表12.1所示.
Table 12.1 TransportConnector properties for updating clients of cluster changes

Property name Default value Description
 updateCluster
Clients
 false If true, pass information to connected clients about changes in the topology of the broker cluster.
rebalanceCluster
Clients
false If true, connected clients will be asked to rebalanceacross a cluster of brokers when a new brokerjoins the network of brokers.
updateClusterClients
OnRemove
false If true, will update clients when a cluster isremoved from the network. Having this as separateoption enables clients to be updated whennew brokers join, but not when brokers leave.
updateClusterFilter null Comma-separated list of regular expression filtersused to match broker names of brokers todesignate as being part of the failover cluster forthe clients.

表12.1 TransportConnector中用于控制代理集群自动更新的属性

属性名称 默认值 描述
 updateCluster
Clients
 false 如果设置为true,当代理集群发送变化时会传递消息给以连接到集群的客户端.
rebalanceCluster
Clients
false 如果设置为true,当新代理加入集群时,客户端会被要求重新为进行进行负载均衡
updateCluster
ClientsOnRemove
false 如果设置为true,当代理集群从代理网络中移除时更新客户端.将这个属性独立出来是为了能够在新代理假加入代理网络时通知客户端,但是移除代理时可以不通知.
updateClusterFilter null 逗号分隔的正则表达式列表,用于匹配代理名称,只有匹配上的代理加入到客户端失效转移代理集群中时,才会更新客户端.
An interesting property is rebalanceClusterClients which, if enabled, ensures thatthe ActiveMQ clients will evenly distribute themselves across the cluster when a newbroker joins. rebalanceClusterClients是一个有趣的属性,启用该属性时,当一个新代理假如集群,ActiveMQ客户端将平均分配它们的负载到集群中所有的代理.
An example configuration for an ActiveMQ broker on a machine named tokyousing these properties is shown next: 使用上述属性,在一台机器名为tokyo机器上配置ActiveMQ的示例代码如下:
<broker>
  ...
  <transportConnectors>
    <transportConnector 
        name="clustered"
        uri="tcp://0.0.0.0:61616"
        updateClusterClients="true"
        updateClusterFilter="*newyork*,*london*" />
  <transportConnectors>
  ...
</broker>
This configuration will update any clients that are using the failover transport protocolwith the locations of any brokers joining that have newyork or london in their brokernames. With updateClusterClients enabled, you only need to configure the failoverprotocol with one broker in the cluster, for example: 上述配置将在代理名称中含有newyork或london的代理加入代理集群中时更新所有使用失效转移传输连接器的客户端.开启updateClusterClients后,你仅需要为集群中的一个代理配置失效转移协议,例如:
failover:(tcp://tokyo:61616)
As the client will be updated automatically as new brokers join and leave the cluster, ifthe machine tokyo should fail, the client would automatically fail over to either newyorkor london. 因为客户端在新代理假如集群,或从集群中移除代理时会自动更新,所以如果名称为tokyo机器宕机了,客户端会自动的进行失效转移从而连接到机器名为newyork或london的代理.
You may wish for your clients to automatically be distributed around all themachines in a cluster, so all the machines share the load of your messaging application.By enabling the property rebalanceClusterClients on the TransportConnector, asActiveMQ brokers join and leave the cluster, this will automatically happen. 你可能希望你的客户端能够自动的针对代理集群中所有的集群进行分布式部署,这样所有的机器可以为消息程序均衡负载.通过启用传输连接器的rebalanceClusterClients属性,在ActiveMQ代理加入集群或从集群中移除代理时,上述客户端针对代理集群进行分布式部署将自动完成.
In this section we’ve taken a deeper look at some the functionality that can beused with the failover transport protocol. You should now have a better understandingof how to configure an ActiveMQ client to detect and survive a network outage orbroker failure. 本节中,我们深入的了解了失效转移连接器的相关功能.现在你应该能够很好的理解如何配置ActiveMQ客户端以便侦测网络问题或代理失效并且在网络发生问题和代理失效是继续工作.
In the next section we’re going to look at scheduling a message to be delivered bythe ActiveMQ broker at some time in the future. 下一节中,我们将看到如何配置ActiveMQ代理的消息调度进行消息的延迟发送.
赞 赏

   微信赞赏  支付宝赞赏


本文固定链接: https://www.jack-yin.com/coding/translation/activemq-in-action/1764.html | 边城网事

该日志由 边城网事 于2013年12月27日发表在 ActiveMQ in Action 读书笔记 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: 12.5 使用 失效转移协议 应对代理或网络故障 | 边城网事

12.5 使用 失效转移协议 应对代理或网络故障 暂无评论

发表评论

快捷键:Ctrl+Enter