1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
| package com.devops.broker.rabbitmq.client;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import java.io.IOException;
import java.util.Random;
class send extends Thread {
private final static String QUEUE_NAME = "hello";
public void run() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("10.6.28.46");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
Random randomIntNumber = new Random();
try {
while (true) {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
Long ThreadID = send.currentThread().getId();
message = message + " Thread ID: " + ThreadID.toString() + " Random Num: " + randomIntNumber.nextInt();
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("Sent '" + message + "'");
System.out.println("");
channel.close();
connection.close();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
class receiver extends Thread {
private final static String QUEUE_NAME = "hello";
public void run() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("10.6.28.46");
factory.setPort(5672);
factory.setUsername("guest");
factory.setPassword("guest");
try {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("Received '" + message + "'");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
send send = new send();
send.start();
receiver receiver = new receiver();
receiver.start();
}
}
|