|
| 1 | +package org.baeldung.spring.amqp; |
| 2 | + |
| 3 | +import java.time.Duration; |
| 4 | +import java.util.Date; |
| 5 | + |
| 6 | +import javax.annotation.PostConstruct; |
| 7 | + |
| 8 | +import org.baeldung.spring.amqp.DestinationsConfig.DestinationInfo; |
| 9 | +import org.slf4j.Logger; |
| 10 | +import org.slf4j.LoggerFactory; |
| 11 | +import org.springframework.amqp.core.AmqpAdmin; |
| 12 | +import org.springframework.amqp.core.AmqpTemplate; |
| 13 | +import org.springframework.amqp.core.Binding; |
| 14 | +import org.springframework.amqp.core.BindingBuilder; |
| 15 | +import org.springframework.amqp.core.Exchange; |
| 16 | +import org.springframework.amqp.core.ExchangeBuilder; |
| 17 | +import org.springframework.amqp.core.MessageListener; |
| 18 | +import org.springframework.amqp.core.Queue; |
| 19 | +import org.springframework.amqp.core.QueueBuilder; |
| 20 | +import org.springframework.amqp.rabbit.listener.MessageListenerContainer; |
| 21 | +import org.springframework.beans.factory.annotation.Autowired; |
| 22 | +import org.springframework.http.MediaType; |
| 23 | +import org.springframework.http.ResponseEntity; |
| 24 | +import org.springframework.web.bind.annotation.GetMapping; |
| 25 | +import org.springframework.web.bind.annotation.PathVariable; |
| 26 | +import org.springframework.web.bind.annotation.PostMapping; |
| 27 | +import org.springframework.web.bind.annotation.RequestBody; |
| 28 | +import org.springframework.web.bind.annotation.RestController; |
| 29 | + |
| 30 | +import reactor.core.publisher.Flux; |
| 31 | +import reactor.core.publisher.Mono; |
| 32 | +import reactor.core.scheduler.Schedulers; |
| 33 | + |
| 34 | +@RestController |
| 35 | +public class AmqpReactiveController { |
| 36 | + |
| 37 | + private static Logger log = LoggerFactory.getLogger(AmqpReactiveController.class); |
| 38 | + |
| 39 | + @Autowired |
| 40 | + private AmqpTemplate amqpTemplate; |
| 41 | + |
| 42 | + @Autowired |
| 43 | + private AmqpAdmin amqpAdmin; |
| 44 | + |
| 45 | + @Autowired |
| 46 | + private DestinationsConfig destinationsConfig; |
| 47 | + |
| 48 | + @Autowired |
| 49 | + private MessageListenerContainerFactory messageListenerContainerFactory; |
| 50 | + |
| 51 | + @PostConstruct |
| 52 | + public void setupQueueDestinations() { |
| 53 | + |
| 54 | + log.info("[I48] Creating Destinations..."); |
| 55 | + |
| 56 | + destinationsConfig.getQueues() |
| 57 | + .forEach((key, destination) -> { |
| 58 | + |
| 59 | + log.info("[I54] Creating directExchange: key={}, name={}, routingKey={}", key, destination.getExchange(), destination.getRoutingKey()); |
| 60 | + |
| 61 | + Exchange ex = ExchangeBuilder.directExchange(destination.getExchange()) |
| 62 | + .durable(true) |
| 63 | + .build(); |
| 64 | + |
| 65 | + amqpAdmin.declareExchange(ex); |
| 66 | + |
| 67 | + Queue q = QueueBuilder.durable(destination.getRoutingKey()) |
| 68 | + .build(); |
| 69 | + |
| 70 | + amqpAdmin.declareQueue(q); |
| 71 | + |
| 72 | + Binding b = BindingBuilder.bind(q) |
| 73 | + .to(ex) |
| 74 | + .with(destination.getRoutingKey()) |
| 75 | + .noargs(); |
| 76 | + |
| 77 | + amqpAdmin.declareBinding(b); |
| 78 | + |
| 79 | + log.info("[I70] Binding successfully created."); |
| 80 | + |
| 81 | + }); |
| 82 | + } |
| 83 | + |
| 84 | + @PostConstruct |
| 85 | + public void setupTopicDestinations() { |
| 86 | + |
| 87 | + // For topic each consumer will have its own Queue, so no binding |
| 88 | + destinationsConfig.getTopics() |
| 89 | + .forEach((key, destination) -> { |
| 90 | + |
| 91 | + log.info("[I98] Creating TopicExchange: name={}, exchange={}", key, destination.getExchange()); |
| 92 | + |
| 93 | + Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) |
| 94 | + .durable(true) |
| 95 | + .build(); |
| 96 | + |
| 97 | + amqpAdmin.declareExchange(ex); |
| 98 | + |
| 99 | + log.info("[I107] Topic Exchange successfully created."); |
| 100 | + |
| 101 | + }); |
| 102 | + } |
| 103 | + |
| 104 | + @PostMapping(value = "/queue/{name}") |
| 105 | + public Mono<ResponseEntity<?>> sendMessageToQueue(@PathVariable String name, @RequestBody String payload) { |
| 106 | + |
| 107 | + // Lookup exchange details |
| 108 | + final DestinationInfo d = destinationsConfig.getQueues() |
| 109 | + .get(name); |
| 110 | + |
| 111 | + if (d == null) { |
| 112 | + // Destination not found. |
| 113 | + return Mono.just(ResponseEntity.notFound() |
| 114 | + .build()); |
| 115 | + } |
| 116 | + |
| 117 | + return Mono.fromCallable(() -> { |
| 118 | + |
| 119 | + log.info("[I51] sendMessageToQueue: queue={}, routingKey={}", d.getExchange(), d.getRoutingKey()); |
| 120 | + amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); |
| 121 | + |
| 122 | + return ResponseEntity.accepted() |
| 123 | + .build(); |
| 124 | + |
| 125 | + }); |
| 126 | + |
| 127 | + } |
| 128 | + |
| 129 | + /** |
| 130 | + * Receive messages for the given queue |
| 131 | + * @param name |
| 132 | + * @param errorHandler |
| 133 | + * @return |
| 134 | + */ |
| 135 | + @GetMapping(value = "/queue/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) |
| 136 | + public Flux<?> receiveMessagesFromQueue(@PathVariable String name) { |
| 137 | + |
| 138 | + DestinationInfo d = destinationsConfig.getQueues() |
| 139 | + .get(name); |
| 140 | + |
| 141 | + if (d == null) { |
| 142 | + return Flux.just(ResponseEntity.notFound() |
| 143 | + .build()); |
| 144 | + } |
| 145 | + |
| 146 | + MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(d.getRoutingKey()); |
| 147 | + |
| 148 | + Flux<String> f = Flux.<String> create(emitter -> { |
| 149 | + |
| 150 | + log.info("[I168] Adding listener, queue={}", d.getRoutingKey()); |
| 151 | + mlc.setupMessageListener((MessageListener) m -> { |
| 152 | + |
| 153 | + String qname = m.getMessageProperties() |
| 154 | + .getConsumerQueue(); |
| 155 | + |
| 156 | + log.info("[I137] Message received, queue={}", qname); |
| 157 | + |
| 158 | + if (emitter.isCancelled()) { |
| 159 | + log.info("[I166] cancelled, queue={}", qname); |
| 160 | + mlc.stop(); |
| 161 | + return; |
| 162 | + } |
| 163 | + |
| 164 | + String payload = new String(m.getBody()); |
| 165 | + emitter.next(payload); |
| 166 | + |
| 167 | + log.info("[I176] Message sent to client, queue={}", qname); |
| 168 | + |
| 169 | + }); |
| 170 | + |
| 171 | + emitter.onRequest(v -> { |
| 172 | + log.info("[I171] Starting container, queue={}", d.getRoutingKey()); |
| 173 | + mlc.start(); |
| 174 | + }); |
| 175 | + |
| 176 | + emitter.onDispose(() -> { |
| 177 | + log.info("[I176] onDispose: queue={}", d.getRoutingKey()); |
| 178 | + mlc.stop(); |
| 179 | + }); |
| 180 | + |
| 181 | + log.info("[I171] Container started, queue={}", d.getRoutingKey()); |
| 182 | + |
| 183 | + }); |
| 184 | + |
| 185 | + |
| 186 | + return Flux.interval(Duration.ofSeconds(5)) |
| 187 | + .map(v -> { |
| 188 | + log.info("[I209] sending keepalive message..."); |
| 189 | + return "No news is good news"; |
| 190 | + }) |
| 191 | + .mergeWith(f); |
| 192 | + } |
| 193 | + |
| 194 | + /** |
| 195 | + * send message to a given topic |
| 196 | + * @param name |
| 197 | + * @param payload |
| 198 | + * @return |
| 199 | + */ |
| 200 | + @PostMapping(value = "/topic/{name}") |
| 201 | + public Mono<ResponseEntity<?>> sendMessageToTopic(@PathVariable String name, @RequestBody String payload) { |
| 202 | + |
| 203 | + // Lookup exchange details |
| 204 | + final DestinationInfo d = destinationsConfig.getTopics() |
| 205 | + .get(name); |
| 206 | + if (d == null) { |
| 207 | + // Destination not found. |
| 208 | + return Mono.just(ResponseEntity.notFound() |
| 209 | + .build()); |
| 210 | + } |
| 211 | + |
| 212 | + return Mono.fromCallable(() -> { |
| 213 | + |
| 214 | + log.info("[I51] sendMessageToTopic: topic={}, routingKey={}", d.getExchange(), d.getRoutingKey()); |
| 215 | + amqpTemplate.convertAndSend(d.getExchange(), d.getRoutingKey(), payload); |
| 216 | + |
| 217 | + return ResponseEntity.accepted() |
| 218 | + .build(); |
| 219 | + |
| 220 | + }); |
| 221 | + } |
| 222 | + |
| 223 | + @GetMapping(value = "/topic/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) |
| 224 | + public Flux<?> receiveMessagesFromTopic(@PathVariable String name) { |
| 225 | + |
| 226 | + DestinationInfo d = destinationsConfig.getTopics() |
| 227 | + .get(name); |
| 228 | + |
| 229 | + if (d == null) { |
| 230 | + return Flux.just(ResponseEntity.notFound() |
| 231 | + .build()); |
| 232 | + } |
| 233 | + |
| 234 | + Queue topicQueue = createTopicQueue(d); |
| 235 | + String qname = topicQueue.getName(); |
| 236 | + |
| 237 | + MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(qname); |
| 238 | + |
| 239 | + Flux<String> f = Flux.<String> create(emitter -> { |
| 240 | + |
| 241 | + log.info("[I168] Adding listener, queue={}", qname); |
| 242 | + |
| 243 | + mlc.setupMessageListener((MessageListener) m -> { |
| 244 | + |
| 245 | + log.info("[I137] Message received, queue={}", qname); |
| 246 | + |
| 247 | + if (emitter.isCancelled()) { |
| 248 | + log.info("[I166] cancelled, queue={}", qname); |
| 249 | + mlc.stop(); |
| 250 | + return; |
| 251 | + } |
| 252 | + |
| 253 | + String payload = new String(m.getBody()); |
| 254 | + emitter.next(payload); |
| 255 | + |
| 256 | + log.info("[I176] Message sent to client, queue={}", qname); |
| 257 | + |
| 258 | + }); |
| 259 | + |
| 260 | + emitter.onRequest(v -> { |
| 261 | + log.info("[I171] Starting container, queue={}", qname); |
| 262 | + mlc.start(); |
| 263 | + }); |
| 264 | + |
| 265 | + emitter.onDispose(() -> { |
| 266 | + log.info("[I176] onDispose: queue={}", qname); |
| 267 | + amqpAdmin.deleteQueue(qname); |
| 268 | + mlc.stop(); |
| 269 | + }); |
| 270 | + |
| 271 | + log.info("[I171] Container started, queue={}", qname); |
| 272 | + |
| 273 | + }); |
| 274 | + |
| 275 | + return Flux.interval(Duration.ofSeconds(5)) |
| 276 | + .map(v -> { |
| 277 | + log.info("[I209] sending keepalive message..."); |
| 278 | + return "No news is good news"; |
| 279 | + }) |
| 280 | + .mergeWith(f); |
| 281 | + |
| 282 | + } |
| 283 | + |
| 284 | + private Queue createTopicQueue(DestinationInfo destination) { |
| 285 | + |
| 286 | + Exchange ex = ExchangeBuilder.topicExchange(destination.getExchange()) |
| 287 | + .durable(true) |
| 288 | + .build(); |
| 289 | + |
| 290 | + amqpAdmin.declareExchange(ex); |
| 291 | + |
| 292 | + Queue q = QueueBuilder.nonDurable() |
| 293 | + .build(); |
| 294 | + |
| 295 | + amqpAdmin.declareQueue(q); |
| 296 | + |
| 297 | + Binding b = BindingBuilder.bind(q) |
| 298 | + .to(ex) |
| 299 | + .with(destination.getRoutingKey()) |
| 300 | + .noargs(); |
| 301 | + |
| 302 | + amqpAdmin.declareBinding(b); |
| 303 | + |
| 304 | + return q; |
| 305 | + } |
| 306 | + |
| 307 | +} |
0 commit comments