rabbitmq教程
来源:互联网 发布:淘宝会员名一般叫什么 编辑:程序博客网 时间:2024/06/05 17:37
F:cd F:\NEW\rabbitmq\mq369rabbitmq-server start1、安装http://erlang.org/download/otp_win64_19.2.exehttp://www.rabbitmq.com/releases/rabbitmq-server/v3.6.6/rabbitmq-server-3.6.6.exehttp://www.rabbitmq.com/configure.html#config-items先安装erlang,再安装rabbitmqD:\tools\erlang64_19.2\erl8.2\binD:\tools\rabbitmq366\rabbitmq_server-3.6.6\sbinjar http://www.rabbitmq.com/releases/rabbitmq-java-client/2\基础配置d:cd D:\tools\rabbitmq366\rabbitmq_server-3.6.6\sbinrabbitmq-server start3、用命令行创建一个test/123456,并让他成为管理员。C:\Users\Administrator>rabbitmqctl add_user test 123456Creating user "test" ...C:\Users\Administrator>rabbitmqctl set_user_tags test administratorSetting tags for user "test" to [administrator] ...4、启用WEB管理C:\Users\Administrator>rabbitmq-plugins enable rabbitmq_managementThe following plugins have been enabled: mochiweb webmachine rabbitmq_web_dispatch amqp_client rabbitmq_management_agent rabbitmq_managementApplying plugin configuration to rabbit@USER-20160620WV... started 6 plugins.192.168.102.191:156725、同理添加369最新版F:cd F:\NEW\rabbitmq\mq369rabbitmq-server startrabbitmqctl set_user_tags test administratorrabbitmq-plugins enable rabbitmq_managementrabbitmqctl change_password guest 1234565、rabbitmqctl 可用命令 wait <pid_file> reset force_reset rotate_logs <suffix> rotate_logs <suffix> hipe_compile <directory> join_cluster <clusternode> [--ram] cluster_status change_cluster_node_type disc | ram forget_cluster_node [--offline] rename_cluster_node oldnode1 newnode1 [oldnode2] [newnode2 ...] update_cluster_nodes clusternode force_boot sync_queue [-p <vhost>] queue cancel_sync_queue [-p <vhost>] queue purge_queue [-p <vhost>] queue set_cluster_name name add_user <username> <password> delete_user <username> change_password <username> <newpassword> clear_password <username> authenticate_user <username> <password> set_user_tags <username> <tag> ... list_users add_vhost <vhost> delete_vhost <vhost> list_vhosts [<vhostinfoitem> ...] set_permissions [-p <vhost>] <user> <conf> <write> <read> clear_permissions [-p <vhost>] <username> list_permissions [-p <vhost>] list_user_permissions <username> set_parameter [-p <vhost>] <component_name> <name> <value> clear_parameter [-p <vhost>] <component_name> <key> list_parameters [-p <vhost>] set_policy [-p <vhost>] [--priority <priority>] [--apply-to <apply-to>]<name> <pattern> <definition> clear_policy [-p <vhost>] <name> list_policies [-p <vhost>] list_queues [-p <vhost>] [--offline|--online|--local] [<queueinfoitem> ...] list_exchanges [-p <vhost>] [<exchangeinfoitem> ...] list_bindings [-p <vhost>] [<bindinginfoitem> ...] list_connections [<connectioninfoitem> ...] list_channels [<channelinfoitem> ...] list_consumers [-p <vhost>] status node_health_check environment report eval <expr> close_connection <connectionpid> <explanation> trace_on [-p <vhost>] trace_off [-p <vhost>] set_vm_memory_high_watermark <fraction> set_vm_memory_high_watermark absolute <memory_limit> set_disk_free_limit <disk_limit> set_disk_free_limit mem_relative <fraction> encode [--decode] [<value>] [<passphrase>] [--list-ciphers] [--list-hashes][--cipher <cipher>] [--hash <hash>] [--iterations <iterations>]<vhostinfoitem> must be a member of the list [name, tracing].The list_queues, list_exchanges and list_bindings commands accept an optionalvirtual host parameter for which to display results. The default value is "/".<queueinfoitem> must be a member of the list [name, durable, auto_delete,arguments, policy, pid, owner_pid, exclusive, exclusive_consumer_pid,exclusive_consumer_tag, messages_ready, messages_unacknowledged, messages,messages_ready_ram, messages_unacknowledged_ram, messages_ram,messages_persistent, message_bytes, message_bytes_ready,message_bytes_unacknowledged, message_bytes_ram, message_bytes_persistent,head_message_timestamp, disk_reads, disk_writes, consumers,consumer_utilisation, memory, slave_pids, synchronised_slave_pids, state].<exchangeinfoitem> must be a member of the list [name, type, durable,auto_delete, internal, arguments, policy].<bindinginfoitem> must be a member of the list [source_name, source_kind,destination_name, destination_kind, routing_key, arguments].<connectioninfoitem> must be a member of the list [pid, name, port, host,peer_port, peer_host, ssl, ssl_protocol, ssl_key_exchange, ssl_cipher,ssl_hash, peer_cert_subject, peer_cert_issuer, peer_cert_validity, state,channels, protocol, auth_mechanism, user, vhost, timeout, frame_max,channel_max, client_properties, recv_oct, recv_cnt, send_oct, send_cnt,send_pend, connected_at].<channelinfoitem> must be a member of the list [pid, connection, name, number,user, vhost, transactional, confirm, consumer_count, messages_unacknowledged,messages_uncommitted, acks_uncommitted, messages_unconfirmed, prefetch_count,global_prefetch_count].
package com.test.rabbitmq;import java.io.IOException;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeoutException;import com.rabbitmq.client.AMQP;import com.rabbitmq.client.BuiltinExchangeType;import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;import com.rabbitmq.client.MessageProperties;import com.rabbitmq.client.ReturnListener;import com.rabbitmq.client.AMQP.BasicProperties;/** * http://www.rabbitmq.com/api-guide.html * * Protocol operations are available through the Channel interface. Connection is used to open channels, register * connection lifecycle event handlers, and close connections that are no longer needed. Connections are instantiated * through ConnectionFactory, which is how you configure various connection settings, such as the vhost or username. * * In software engineering, a connection broker is a resource manager that manages a pool of connections to * connection-based resources such as databases or remote desktops, enabling rapid reuse of these connections by * short-lived processes without the overhead of setting up a new connection each * * @date 2017年4月19日 上午11:31:41 */public class MqMessageSender { public static void main(String args[]) { for (int i = 0; i < 30; i++) { test(); System.out.println(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } while (true) { ; } } public static void test() { String username = "test"; String password = "123456"; String host = "192.168.102.191"; int port = 5672; String virtualHost = "/"; String exchangeName = "exchangeName"; String routingKey = "routingKey.test2"; ConnectionFactory factory = new ConnectionFactory();// 里面可以各种设置 factory.setUsername(username); factory.setPassword(password); factory.setHost(host); ; // factory.setConnectionTimeout(timeout); // factory.setHandshakeTimeout(timeout); factory.setVirtualHost(virtualHost); factory.setPort(port); // factory.useNio(); // factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost"); Connection connection = null; Channel channel = null; // public static final BuiltinExchangeType DIRECT; // public static final BuiltinExchangeType FANOUT; // public static final BuiltinExchangeType TOPIC; // public static final BuiltinExchangeType HEADERS; // Direct Exchange – 处理路由键。需要将一个队列绑定到交换机上,要求该消息与一个特定的路由键完全匹配 // Fanout Exchange – // 不处理路由键。你只需要简单的将队列绑定到交换机上。一个发送到交换机的消息都会被转发到与该交换机绑定的所有队列上。很像子网广播,每台子网内的主机都获得了一份复制的消息。Fanout交换机转发消息是最快的。 // Topic Exchange – // 将路由键和某模式进行匹配。此时队列需要绑定要一个模式上。符号“#”匹配一个或多个词,符号“*”匹配不多不少一个词。因此“audit.#”能够匹配到“audit.irs.corporate”,但是“audit.*” // 只会匹配到“audit.irs” // // 在AMQP模型中,Exchange是接受生产者消息并将消息路由到消息队列的关键组件。 try { connection = factory.newConnection(); channel = connection.createChannel(); // channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, context.isDefaultDurable(), false, // null); // channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC, true, false, null); // {//单一的,排他的,只有一个client // a durable, non-autodelete exchange of "direct" type // a non-durable, exclusive, autodelete queue with a generated name // channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true); // String queueName = channel.queueDeclare().getQueue(); // channel.queueBind(queueName, exchangeName, routingKey);//The above function calls then bind the queue to // } // the exchange with the given routing key. // channel.basicPublish("exchangeName", "routingKey", MessageProperties.PERSISTENT_TEXT_PLAIN, // messageBodyBytes); // { // // a durable, non-autodelete exchange of "direct" type // // a durable, non-exclusive, non-autodelete queue with a well-known name // //// String queueName = "queue_test"; //// channel.exchangeDeclare(exchangeName, "direct", true); //// channel.queueDeclare(queueName, true, false, false, null); //// channel.queueBind(queueName, exchangeName, routingKey); // } byte[] messageBodyBytes = new Date().toString().getBytes(); System.out.println(new Date().toString()); // channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes); // { // 处理不能路由的消息 If a message is published with the "mandatory" flags set, but cannot be routed, the broker // will return // it to the sending client (via a AMQP.Basic.Return command). // For fine control, you can use overloaded variants to specify the mandatory flag, or send messages // with pre-set message properties // This sends a message with delivery mode 2 (persistent), priority 1 and content-type "text/plain". channel.addReturnListener(new ReturnListener() { @Override public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, BasicProperties properties, byte[] body) throws IOException { // TODO Auto-generated method stub System.out.println("消息没找到队列" + new Date().toString()); System.out.println("" + replyCode + "," + replyText + "," + exchange + "," + routingKey + "," + new String(body, "utf-8")); System.out.println(properties); } }); channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, null); channel.basicPublish(exchangeName, routingKey, true, MessageProperties.PERSISTENT_TEXT_PLAIN, messageBodyBytes); // System.out.println("end"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // } // { // // You can build your own message properties object, using a Builder class mentioning as many properties // // as you like, for example: // channel.basicPublish(exchangeName, routingKey, new AMQP.BasicProperties.Builder() // .contentType("text/plain").deliveryMode(2).priority(1).userId("bob").build(), messageBodyBytes); // } // { // // This example publishes a message with custom headers,with expiration: // Map<String, Object> headers = new HashMap<String, Object>(); // headers.put("latitude", 51.5252949); // headers.put("longitude", -0.0905493); // channel.basicPublish(exchangeName, routingKey, // new AMQP.BasicProperties.Builder().headers(headers).expiration("6000").build(), // messageBodyBytes); // } // Channels and Concurrency Considerations (Thread Safety) // Channel instances must not be shared between threads. Applications should prefer using a Channel per // thread instead of sharing the same Channel across multiple threads. // While some operations on channels are safe to invoke concurrently, some are not and will result in // incorrect frame interleaving on the wire. // Sharing channels between threads will also interfere with * Publisher Confirms. } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { disconnect(connection, channel); } } public static void disconnect(Connection connection, Channel channel) { try { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) {// channel e.printStackTrace(); } }}
package com.test.rabbitmq;import java.io.IOException;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeoutException;import com.rabbitmq.client.AMQP;import com.rabbitmq.client.Address;import com.rabbitmq.client.AddressResolver;import com.rabbitmq.client.BuiltinExchangeType;import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory;import com.rabbitmq.client.Consumer;import com.rabbitmq.client.DefaultConsumer;import com.rabbitmq.client.DnsRecordIpAddressResolver;import com.rabbitmq.client.DnsSrvRecordAddressResolver;import com.rabbitmq.client.Envelope;import com.rabbitmq.client.ExceptionHandler;import com.rabbitmq.client.GetResponse;import com.rabbitmq.client.MessageProperties;import com.rabbitmq.client.MetricsCollector;import com.rabbitmq.client.ShutdownListener;import com.rabbitmq.client.ShutdownSignalException;import com.rabbitmq.client.TopologyRecoveryException;import com.rabbitmq.client.impl.Method;import com.rabbitmq.client.impl.nio.NioParams;/** * Protocol operations are available through the Channel interface. Connection is used to open channels, register * connection lifecycle event handlers, and close connections that are no longer needed. Connections are instantiated * through ConnectionFactory, which is how you configure various connection settings, such as the vhost or username. * * In software engineering, a connection broker is a resource manager that manages a pool of connections to * connection-based resources such as databases or remote desktops, enabling rapid reuse of these connections by * short-lived processes without the overhead of setting up a new connection each * * @date 2017年4月19日 上午11:31:41 */public class MqMessageConsumer { String username = "test"; String password = "123456"; String host = "192.168.102.191"; int port = 5672; String virtualHost = "/"; String exchangeName = "exchangeName"; String routingKey = "routingKey.test1"; ConnectionFactory factory = new ConnectionFactory();// 里面可以各种设置 { factory.setUsername(username); factory.setPassword(password); factory.setHost(host); ; // factory.setConnectionTimeout(timeout); // factory.setHandshakeTimeout(timeout); factory.setVirtualHost(virtualHost); factory.setPort(port); // factory.useNio(); // factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost"); } public static void main(String args[]) { new MqMessageConsumer().test(); } public void test() { Connection connection = null; // final Channel channel = null; try { connection = factory.newConnection(); final Channel channel = connection.createChannel(); String queueName = "queue_test"; channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); // channel.confirmSelect();//用来对sender发送确认 // The AMQP 0-9-1 connection and channel share the same general approach to managing network failure, // internal failure, and explicit local shutdown. // The AMQP 0-9-1 connection and channel have the following lifecycle states: // open: the object is ready to use // closing: the object has been explicitly notified to shut down locally, has issued a shutdown request to // any supporting lower-layer objects, and is waiting for their shutdown procedures to complete // closed: the object has received all shutdown-complete notification(s) from any lower-layer objects, and // as a consequence has shut itself down // addShutdownListener(ShutdownListener listener) and removeShutdownListener(ShutdownListener // addShutdownListener(ShutdownListener listener) and removeShutdownListener(ShutdownListener listener), to // manage any listeners, which will be fired when the object transitions to closed state. Note that, adding // a ShutdownListener to an object that is already closed will fire the listener immediately // getCloseReason(), to allow the investigation of what was the reason of the object’s shutdown // isOpen(), useful for testing whether the object is in an open state // close(int closeCode, String closeMessage), to explicitly notify the object to shut down channel.addShutdownListener(new ShutdownListener() { @Override public void shutdownCompleted(ShutdownSignalException shutdownSignalException) { // By calling the isHardError() method we get information whether it was a connection or a channel // error, and getReason() returns information about the cause, in the form an AMQP method - either // AMQP.Channel.Close or AMQP.Connection.Close (or null if the cause was some exception in the // library, such as a network communication failure, in which case that exception can be retrieved // with getCause()). System.out.println("shutdownSignalException error"); System.out.println(channel.getCloseReason()); // Use of the isOpen() method of channel and connection objects is not recommended for production // code, because the value returned by the method is dependent on the existence of the shutdown // cause。 // Instead, we should normally ignore such checking, and simply attempt the action desired. If // during the execution of the code the channel of the connection is closed, a // ShutdownSignalException will be thrown indicating that the object is in an invalid state. We // should also catch for IOException caused either by SocketException, when broker closes the // connection unexpectedly, or ShutdownSignalException, when broker initiated clean close. System.out.println(channel.isOpen());// 生产环境不应该用isOpen()方法,因为这个依赖其他操作,应该直接操作不判断状态,等到相应操作时会报错,根据错误原因判断状态 if (shutdownSignalException.isHardError()) {// Connection connection = (Connection) shutdownSignalException.getReference(); if (!shutdownSignalException.isInitiatedByApplication()) { Method reason = (Method) shutdownSignalException.getReason(); System.out.println(reason.toString()); } System.out.println(connection.toString()); } else { Channel channel = (Channel) shutdownSignalException.getReference(); } shutdownSignalException.printStackTrace(); } }); System.out.println(System.currentTimeMillis()); {// 循环获取消息 boolean autoAck = false; // 一个channel最好一个consumer,因为每个channel有自己的分发线程 channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) { // handleShutdownSignal is called when channels and connections close, and handleConsumeOk is passed // the // consumer tag before any other callbacks to that Consumer are called. // Consumers can also implement the handleCancelOk and handleCancel methods to be notified of // explicit // and implicit cancellations, respectively. @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { System.out.println(envelope.toString()); String routingKey = envelope.getRoutingKey(); String contentType = properties.getContentType(); long deliveryTag = envelope.getDeliveryTag(); System.out.println(new String(body, "utf-8")); // (process the message components here ...) channel.basicAck(deliveryTag, false); } }); } // {//只获取一个消息 // boolean autoAck=false; // GetResponse getResponse=channel.basicGet(queueName, false); // if (getResponse==null) { // System.out.println("no getResponse"); // } else { // System.out.println(getResponse.toString()); // AMQP.BasicProperties basicProperties=getResponse.getProps(); // String body=new String(getResponse.getBody(), "utf-8"); // long deliveryTag=getResponse.getEnvelope().getDeliveryTag(); // channel.basicAck(deliveryTag, false); // } // } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { // disconnect(connection, null); } } public void disconnect(Connection connection, Channel channel) { try { if (channel != null) { channel.close(); } if (connection != null) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) {// channel e.printStackTrace(); } } /** 判断是否可用 */ public void validMethod(Channel channel) { // <rabbit:listener-container prefetch="1" > try { channel.basicQos(1); // /** // * Request specific "quality of service" settings. // * // * These settings impose limits on the amount of data the server // * will deliver to consumers before requiring acknowledgements. // * Thus they provide a means of consumer-initiated flow control. // * @see com.rabbitmq.client.AMQP.Basic.Qos // * @param prefetchSize maximum amount of content (measured in // * octets) that the server will deliver, 0 if unlimited // * @param prefetchCount maximum number of messages that the server // * will deliver, 0 if unlimited // * @param global true if the settings should be applied to the // * entire channel rather than each consumer // * @throws java.io.IOException if an error is encountered // */ // void basicQos(int prefetchSize, int prefetchCount, boolean global) throws IOException; } catch (ShutdownSignalException sse) { // possibly check if channel was closed // by the time we started action and reasons for // closing it } catch (IOException ioe) { // check why connection was closed } } /** * Consumer thread pool * * Consumer threads (see Receiving below) are automatically allocated in a new ExecutorService thread pool by * default. If greater control is required supply an ExecutorService on the newConnection() method, so that this * pool of threads is used instead. Here is an example where a larger thread pool is supplied than is normally * allocated: * * Both Executors and ExecutorService classes are in the java.util.concurrent package. When the connection is closed * a default ExecutorService will be shutdown(), but a user-supplied ExecutorService (like es above) will not be * shutdown(). Clients that supply a custom ExecutorService must ensure it is shutdown eventually (by calling its * shutdown() method), or else the pool’s threads may prevent JVM termination. * * The same executor service may be shared between multiple connections, or serially re-used on re-connection but it * cannot be used after it is shutdown(). * * Use of this feature should only be considered if there is evidence that there is a severe bottleneck in the * processing of Consumer callbacks. If there are no Consumer callbacks executed, or very few, the default * allocation is more than sufficient. The overhead is initially minimal and the total thread resources allocated * are bounded, even if a burst of consumer activity may occasionally occur. */ public void setExecutor() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory();// 里面可以各种设置 factory.setUsername(username); factory.setPassword(password); factory.setHost(host); factory.setVirtualHost(virtualHost); factory.setPort(port); ExecutorService es = Executors.newFixedThreadPool(20); Connection conn = factory.newConnection(es); } /** * will attempt to connect to hostname1:portnumber1, and if that fails to hostname2:portnumber2. The connection * returned is the first in the array that succeeds (without throwing IOException). This is entirely equivalent to * repeatedly setting host and port on a factory, calling factory.newConnection() each time, until one of them * succeeds. If an ExecutorService is provided as well (using the form factory.newConnection(es, addrArr)) the * thread pool is associated with the (first) successful connection. */ public void setHosts() { // Address[] addrArr = new Address[] { new Address(hostname1, portnumber1), new Address(hostname2, portnumber2) // }; // Connection conn = factory.newConnection(addrArr); } /** * As of version 3.6.6, it is possible to let an implementation of AddressResolver choose where to connect when * creating a connection: * * Connection conn = factory.newConnection(addressResolver); The AddressResolver interface is like the following: * public interface AddressResolver { * * List<Address> getAddresses() throws IOException; * * } Just like with a list of hosts, the first Address returned will be tried first, then the second if the client * fails to connect to the first, and so on. If an ExecutorService is provided as well (using the form * factory.newConnection(es, addressResolver)) the thread pool is associated with the (first) successful connection. * * The AddressResolver is the perfect place to implement custom service discovery logic, which is especially useful * in a dynamic infrastructure. Combined with automatic recovery, the client can automatically connect to nodes that * weren't even up when it was first started. Affinity and load balancing are other scenarios where a custom * AddressResolver could be useful. * * The Java client ships with the following implementations (see the javadoc for details): * * DnsRecordIpAddressResolver: given the name of a host, returns its IP addresses (resolution against the platform * DNS server). This can be useful for simple DNS-based load balancing or failover. DnsSrvRecordAddressResolver: * given the name of a service, returns hostname/port pairs. The search is implemented as a DNS SRV request. This * can be useful when using a service registry like HashiCorp Consul. */ public void setServiceDiscovery() { AddressResolver addressResolver = new AddressResolver() { @Override public List<Address> getAddresses() throws IOException { return null; } }; // DnsRecordIpAddressResolver dnsRecordIpAddressResolver=new DnsRecordIpAddressResolver(); // DnsSrvRecordAddressResolver dnsSrvRecordAddressResolver=new DnsSrvRecordAddressResolver(exchangeName); } /** * The heartbeat timeout value defines after what period of time the peer TCP connection should be considered * unreachable (down) by RabbitMQ and client libraries. This value is negotiated between the client and RabbitMQ * server at the time of connection. The client must be configured to request heartbeats. In RabbitMQ versions 3.0 * and higher, the broker will attempt to negotiate heartbeats by default (although the client can still veto them). * The timeout is in seconds, and default value is 60 (580 prior to release 3.5.5). * * Heartbeat frames are sent about every timeout / 2 seconds. After two missed heartbeats, the peer is considered to * be unreachable. Different clients manifest this differently but the TCP connection will be closed. When a client * detects that RabbitMQ node is unreachable due to a heartbeat, it needs to re-connect. * * Any traffic (e.g. protocol operations, published messages, acknowledgements) counts for a valid heartbeat. * Clients may choose to send heartbeat frames regardless of whether there was any other traffic on the connection * but some only do it when necessary. * * Heartbeats can be disabled by setting the timeout interval to 0. This is not a recommended practice. * * Note that in case RabbitMQ server has a non-zero heartbeat timeout configured (which is the default in versions * starting with 3.6.x), the client can only lower the value but not increase it. * Values within the 5 to 20 * seconds range are optimal for most environments. */ public void setHeatbeats() { factory.setRequestedHeartbeat(60);// set the heartbeat timeout to 60 seconds } /** * Version 4.0 of the Java client brings experimental support for Java non-blocking IO (a.k.a Java NIO). NIO isn't * supposed to be faster than blocking IO, it simply allows to control resources (in this case, threads) more * easily. * * With the default blocking IO mode, each connection uses a thread to read from the network socket. With the NIO * mode, you can control the number of threads that read and write from/to the network socket. * * Use the NIO mode if your Java process uses many connections (dozens or hundreds). You should use fewer threads * than with the default blocking mode. With the appropriate number of threads set, you shouldn't experiment any * decrease in performance, especially if the connections are not so busy. * * NIO must be enabled explicitly: * * ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.useNio(); The NIO mode can be * configured through the NioParams class: * * connectionFactory.setNioParams(new NioParams().setNbIoThreads(4)); The NIO mode uses reasonable defaults, but you * may need to change them according to your own workload. Some of the settings are: the total number of IO threads * used, the size of buffers, a service executor to use for the IO loops, parameters for the in-memory write queue * (write requests are enqueued before being sent on the network). Please read the Javadoc for details and defaults. */ public void setNio() { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.useNio(); connectionFactory.setNioParams(new NioParams().setNbIoThreads(4)); } /** * abbitMQ Java client supports automatic recovery of connections and topology (queues, exchanges, bindings, and * consumers). The automatic recovery process for many applications follows the following steps: * * Reconnect, Restore connection listeners ,Re-open channels, Restore channel listeners ,Restore channel basic.qos * setting, publisher confirms and transaction settings * * Topology recovery includes the following actions, performed for every channel: Re-declare exchanges (except for * predefined ones) Re-declare queues Recover all bindings, Recover all consumers. As of version 4.0.0 of the Java * client, automatic recovery is enabled by default (and thus topology recovery as well). * * If recovery fails due to an exception (e.g. RabbitMQ node is still not reachable), it will be retried after a * fixed time interval (default is 5 seconds). The interval can be configured. * * When a list of addresses is provided, the list is shuffled and all addresses are tried, one after the next: */ public void setConnectionRecovery() { factory.setAutomaticRecoveryEnabled(true);// To disable or enable automatic connection recovery factory.setNetworkRecoveryInterval(10000);//// attempt recovery every 10 seconds { // enable automatic recovery (e.g. Java client prior 4.0.0) factory.setAutomaticRecoveryEnabled(true); // disable topology recovery // factory.setTopologyRecoveryEnabled(false); factory.setTopologyRecoveryEnabled(false); } } /** * It is possible to register one or more recovery listeners on recoverable connections and channels. When * connection recovery is enabled, connections returned by ConnectionFactory#newConnection and * Connection#createChannel implement com.rabbitmq.client.Recoverable. * * Note that you currently need to cast connections and channels to Recoverable in order to use those methods. */ public void addRecoveryListener(Connection connection) { // connection.set // can't find in amqp-clinet-4.1.0 throw new RuntimeException("not support"); } /** * To enable confirms, a client sends the confirm.select method. Depending on whether no-wait was set or not, the * broker may respond with a confirm.select-ok. Once the confirm.select method is used on a channel, it is said to * be in confirm mode. A transactional channel cannot be put into confirm mode and once a channel is in confirm * mode, it cannot be made transactional. * * Once a channel is in confirm mode, both the broker and the client count messages (counting starts at 1 on the * first confirm.select). The broker then confirms messages as it handles them by sending a basic.ack on the same * channel. The delivery-tag field contains the sequence number of the confirmed message. The broker may also set * the multiple field in basic.ack to indicate that all messages up to and including the one with the sequence * number have been handled. * * An example in Java that publishes a large number of messages to a channel in confirm mode and waits for the * acknowledgements can be found here. * * Delivery tag is a 64 bit long value, and thus its maximum value is 9223372036854775807. Since delivery tags are * scoped per channel, it is very unlikely that a publisher or consumer will run over this value in practice. */ public void setConfirms() { } /** * Unhandled exceptions related to connection, channel, recovery, and consumer lifecycle are delegated to the * exception handler. Exception handler is any object that implements the ExceptionHandler interface. By default, an * instance of DefaultExceptionHandler is used. It prints exception details to the standard output. Exception * handlers should be used for exception logging. * * @param factory */ public void setExceptionHandler(ConnectionFactory factory) { factory.setExceptionHandler(new ExceptionHandler() { @Override public void handleUnexpectedConnectionDriverException(Connection connection, Throwable throwable) { } @Override public void handleTopologyRecoveryException(Connection connection, Channel channel, TopologyRecoveryException topologyrecoveryexception) { } @Override public void handleReturnListenerException(Channel channel, Throwable throwable) { } @Override public void handleFlowListenerException(Channel channel, Throwable throwable) { } @Override public void handleConsumerException(Channel channel, Throwable throwable, Consumer consumer, String s, String s1) { } @Override public void handleConnectionRecoveryException(Connection connection, Throwable throwable) { } @Override public void handleConfirmListenerException(Channel channel, Throwable throwable) { } @Override public void handleChannelRecoveryException(Channel channel, Throwable throwable) { } @Override public void handleBlockedListenerException(Connection connection, Throwable throwable) { } }); } /** * As of version 4.0.0, the client gathers runtime metrics (e.g. number of published messages). Metrics collection * is optional and is set up at the ConnectionFactory level, using the setMetricsCollector(metricsCollector) method. * This method expects a MetricsCollector instance, which is called in several places of the client code. * * The client ships with a MetricsCollector implementation that uses the Dropwizard Metrics library. One can enable * the metrics collection the following way: Here are the collected metrics: * * Number of open connections (a Counter in the default implementation) Number of open channels (a Counter in the * default implementation) Number of published messages (a Meter in the default implementation) Number of consumed * messages (a Meter in the default implementation) Number of acknowledged messages (a Meter in the default * implementation) Number of rejected messages (a Meter in the default implementation) * * @param factory */ public void setMetricsAndMonitor(ConnectionFactory factory) { factory.setMetricsCollector(new MetricsCollector() { @Override public void newConnection(Connection connection) { // TODO Auto-generated method stub } @Override public void newChannel(Channel channel) { // TODO Auto-generated method stub } @Override public void consumedMessage(Channel channel, long l, String s) { // TODO Auto-generated method stub } @Override public void consumedMessage(Channel channel, long l, boolean flag) { // TODO Auto-generated method stub } @Override public void closeConnection(Connection connection) { // TODO Auto-generated method stub } @Override public void closeChannel(Channel channel) { // TODO Auto-generated method stub } @Override public void basicReject(Channel channel, long l) { // TODO Auto-generated method stub } @Override public void basicPublish(Channel channel) { // TODO Auto-generated method stub } @Override public void basicNack(Channel channel, long l) { // TODO Auto-generated method stub } @Override public void basicConsume(Channel channel, String s, boolean flag) { // TODO Auto-generated method stub } @Override public void basicCancel(Channel channel, String s) { // TODO Auto-generated method stub } @Override public void basicAck(Channel channel, long l, boolean flag) { // TODO Auto-generated method stub } }); } /** * Caveats and Limitations * * To make topology recovery possible, RabbitMQ Java client maintains a cache of declared queues, exchanges, and * bindings. The cache is per-connection. Certain RabbitMQ features make it impossible for clients to observe some * topology changes, e.g. when a queue is deleted due to TTL. RabbitMQ Java client tries to invalidate cache entries * in the most common cases: * * When queue is deleted. When exchange is deleted. When binding is deleted. When consumer is cancelled on an * auto-deleted queue. When queue or exchange is unbound from an auto-deleted exchange. However, the client cannot * track these topology changes beyond a single connection. Applications that rely on auto-delete queues or * exchanges, as well as queue TTL (note: not message TTL!), and use automatic connection recovery, should * explicitly delete entities know to be unused or deleted, to purge client-side topology cache. This is facilitated * by Channel#queueDelete, Channel#exchangeDelete, Channel#queueUnbind, and Channel#exchangeUnbind being idempotent * in RabbitMQ 3.3.x (deleting what's not there does not result in an exception). */ public void getLimitation() { }}
0 0
- rabbitmq教程
- RabbitMq安装快速教程
- RabbitMQ入门级教程
- RabbitMQ入门级教程
- RabbitMQ 教程一
- centos7 rabbitMq 安装教程
- 有关RabbitMQ教程网站
- RabbitMQ安装教程
- rabbitMq下载、安装教程
- RabbitMQ教程总结
- RabbitMQ安装教程
- 【RabbitMQ】——centos7安装rabbitmq教程
- rabbitmq 教程 一 hello world
- rabbitmq 教程 二 Work Queues
- rabbitmq 教程 三 Publish/Subscribe
- Rabbitmq教程翻译(一)introduction
- Rabbitmq教程翻译(四)routing
- RabbitMQ官网教程---简介
- HTTP --- 头部详细解释
- 内核文件路径正则匹配
- 二叉树之后序遍历
- 堆内存和栈内存的概念
- 简单搭建Nginx+Tomcat负载均衡
- rabbitmq教程
- 集合相等问题
- Hive操作Hbase
- EXP-00002错误解决方法
- HTTP协议三次握手,四次挥手过程
- java学习随记
- Linux进程/线程协作 之 创建指定数量的进程
- 素数筛法-水题
- 深度学习笔记:优化方法总结(BGD,SGD,Momentum,AdaGrad,RMSProp,Adam)