Hands-On: AMQP-ish Routing
We can’t import RabbitMQ libs here, so let’s model routing decisions with standard collections.
xxxxxxxxxx
48
}
// file: RoutingDemo.java
// Simulate AMQP-style direct vs topic routing with plain Java maps (no external deps).
import java.util.*;
import java.util.function.Predicate;
class Message { String key; String body; Message(String k, String b){ key=k; body=b; } }
interface QueueLike { void push(Message m); List<Message> drain(); }
class MemoryQueue implements QueueLike {
private final LinkedList<Message> q = new LinkedList<>();
public void push(Message m){ q.add(m); }
public List<Message> drain(){ List<Message> out=new ArrayList<>(q); q.clear(); return out; }
}
public class RoutingDemo {
// Binding for "direct": exact match on routing key
static Map<String, QueueLike> directBindings = new HashMap<>();
// Binding for "topic": predicate over routing key (very simplified)
static Map<Predicate<String>, QueueLike> topicBindings = new HashMap<>();
static void publishDirect(Message m){
QueueLike q = directBindings.get(m.key);
if(q!=null) q.push(m);
}
static void publishTopic(Message m){
topicBindings.forEach((pred,q)->{ if(pred.test(m.key)) q.push(m); });
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment