-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
QueueConsumer.java
92 lines (81 loc) · 2.54 KB
/
QueueConsumer.java
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
package mock.contract;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author pthomas3
*/
public class QueueConsumer {
private static final Logger logger = LoggerFactory.getLogger(QueueConsumer.class);
private final Connection connection;
private final MessageConsumer consumer;
private final String queueName;
private final Session session;
public QueueConsumer(String queueName) {
this.queueName = queueName;
this.connection = QueueUtils.getConnection();
try {
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
consumer = session.createConsumer(destination);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void listen(java.util.function.Consumer<String> handler) {
setMessageListener(message -> {
TextMessage tm = (TextMessage) message;
try {
handler.accept(tm.getText());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
public void setMessageListener(MessageListener ml) {
try {
consumer.setMessageListener(ml);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String waitForNextMessage() {
try {
TextMessage tm = (TextMessage) consumer.receive();
return tm.getText();
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
public void purgeMessages() {
try {
consumer.setMessageListener(null);
while (true) {
Message message = consumer.receive(50);
if (message == null) {
logger.info("*** no more messages to purge: {}", queueName);
break;
}
logger.info("*** purged message: {} - {}", queueName, message);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void stop() {
try {
consumer.close();
session.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}