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
91
92
93
94
95
96
|
package org.apache.qpid.example.amqpexample.direct;
import java.nio.ByteBuffer;
import org.apache.qpid.api.Message;
import org.apache.qpid.nclient.Client;
import org.apache.qpid.nclient.Connection;
import org.apache.qpid.nclient.Session;
import org.apache.qpid.nclient.util.MessageListener;
import org.apache.qpid.transport.DeliveryProperties;
import org.apache.qpid.transport.Header;
import org.apache.qpid.transport.MessageAcceptMode;
import org.apache.qpid.transport.MessageAcquireMode;
public class DirectProducer implements MessageListener
{
boolean finish = false;
public void onMessage(Message m)
{
String data = null;
try
{
ByteBuffer buf = m.readData();
byte[] b = new byte[buf.remaining()];
buf.get(b);
data = new String(b);
}
catch(Exception e)
{
System.out.print("Error reading message");
e.printStackTrace();
}
System.out.println("Message: " + data);
if (data != null && data.equals("That's all, folks!"))
{
finish = true;
}
}
public boolean isFinished()
{
return finish;
}
public static void main(String[] args)
{
// Create connection
Connection con = Client.createConnection();
try
{
con.connect("localhost", 5672, "test", "guest", "guest");
}
catch(Exception e)
{
System.out.print("Error connecting to broker");
e.printStackTrace();
}
// Create session
Session session = con.createSession(0);
DeliveryProperties deliveryProps = new DeliveryProperties();
deliveryProps.setRoutingKey("routing_key");
for (int i=0; i<10; i++)
{
session.messageTransfer("amq.direct", MessageAcceptMode.EXPLICIT,MessageAcquireMode.PRE_ACQUIRED,
new Header(deliveryProps),
"Message " + i);
}
session.messageTransfer("amq.direct", MessageAcceptMode.EXPLICIT, MessageAcquireMode.PRE_ACQUIRED,
new Header(deliveryProps),
"That's all, folks!");
// confirm completion
session.sync();
//cleanup
session.sessionDetach(session.getName());
try
{
con.close();
}
catch(Exception e)
{
System.out.print("Error closing broker connection");
e.printStackTrace();
}
}
}
|