Java RABBITMQ Complete example with join disconnect recovery, full sample release receive __java

Source: Internet
Author: User
Tags uuid rabbitmq

Java RABBITMQ Complete example with join disconnect recovery, full sample publish Receive




Import java.io.IOException;
Import Java.util.UUID;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.TimeUnit;

Import java.util.concurrent.TimeoutException;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import com.rabbitmq.client.ConsumerCancelledException;
Import Com.rabbitmq.client.QueueingConsumer;
Import Com.rabbitmq.client.QueueingConsumer.Delivery;

Import com.rabbitmq.client.ShutdownSignalException;

	* * @rabbitmq Data Test * */public class Rabbitmqtest {//queue name private final static String queue_name = "Hello";
	Create pairs like connectionfactory factory;
	Join Information Connection Connection;

	Channel Channel Channel = null;

	Gets the data queue queueingconsumer consumer = null; /** * INITMQ Initialization MQ Information * * * */public void Initmq () {//open connection and create channel, same as sending end factory = new ConnectionFactory ()
		; FactoRy.sethost ("192.168.2.110");
		Factory.setusername ("RABBITMQ");
		Factory.setpassword ("RABBITMQ");
		Factory.setvirtualhost ("/");
		Factory.setport (5672);
		Key, specifies the thread pool executorservice service = Executors.newfixedthreadpool (10);
		Factory.setsharedexecutor (service);
		Set Automatic recovery factory.setautomaticrecoveryenabled (TRUE); Factory.setnetworkrecoveryinterval (2);/Set No 10s, retry once factory.settopologyrecoveryenabled (false),/set do not declare exchanger,
		Queues and other information.

			try {connection = factory.newconnection ();
			Channel = Connection.createchannel ();
			Declares queues, primarily to prevent message recipients from running the program, and to create queues when they do not exist.

			Channel.queuedeclare (Queue_name, False, False, false, NULL); System.out. println ("[*] waiting for messages."

			To exit Press CTRL + C ");
			Set up a strip of response Channel.basicqos (0, 1, false);
			Create Queue Consumer consumer = new Queueingconsumer (channel);

		Specifies the consumption queue, and the second parameter false indicates that Channel.basicconsume (Queue_name, false, consumer) are not answered automatically; catch (IOException e) {//TODO auto-generated catch block E.printStackTrace ();
		catch (TimeoutException e) {//TODO auto-generated catch block E.printstacktrace (); }/** * Cyclesend call thread pool to send data <br/> * * */public void Cyclesend () {//Use thread pool Scheduledexecutor
		Service Scheduledthreadpool = executors. Newscheduledthreadpool (5);
				Timed Task Scheduledthreadpool.scheduleatfixedrate (new Runnable () {@Override public void run () {//Sent message
				String message = "Hello world!" + uuid.randomuuid ();
						TODO auto-generated Method Stub try {if (!channel.isopen ()) {//Initialize recovery//INITMQ ();
					System.out.println ("[x] initiates send Resend" +channel.isopen ());
					} if (Channel.isopen ()) {Channel.basicpublish ("", queue_name, NULL, message.getbytes ());

				The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();

	}}, 1, 3, timeunit.seconds); /** * RECEIVEMQ collects data from MQ <br/> * and can harvest MQ information data * */Public void Receivemq () {Thread thr = new Thread (new Runnable () {@Override public void run () {Cycle ();

		}
		});

	Thr.start ();

	//Whether to disconnect Boolean isbroken = false; Circular read data protected void Cycle () {while (true) {//Nextdelivery is a blocking method (the internal implementation is actually the take method of blocking queues) QUEUEINGCONSUMER.D
			Elivery delivery;

					try {if (IsBroken) {//channel.basicrecover ();
					
				System.out.println ("[x] start receiving data may be card----" + channel.isopen ());
					} if (Channel.isopen ()) {delivery = Consumer.nextdelivery ();
					String message = new String (Delivery.getbody ());

					Answer Channel.basicack (Delivery.getenvelope (). Getdeliverytag (), false);
				System.out.println ("[X] Received '" + Message + "'"); } catch (Shutdownsignalexception e) {try {if (Channel.isopen ()) {//exception recovery consumer = new Qu
						Eueingconsumer (channel);
						Channel.basicconsume (Queue_name, false, consumer);
						IsBroken = false; System.out.println ("[X] Restore Success" –--");
					} catch (Exception e1) {IsBroken = true;
					TODO auto-generated Catch block E1.printstacktrace ();

				System.out.println ("[x] receives thread---shutdownsignalexception-exception");
			//TODO auto-generated catch block//E.printstacktrace ();
				catch (Consumercancelledexception e) {//TODO auto-generated catch block E.printstacktrace ();
			System.out.println ("[x] receive thread hop----consumercancelledexception");
				catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();

				System.out.println ("[x] receive thread jumps out----Exception");
			Break
 }

		}

	}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.