Java tutorial
/** * Copyright Suchkov Dmitrii * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codio.collab.core.queue; import com.codio.collab.core.Context; import com.codio.collab.core.interfaces.BackendProcessor; import com.codio.collab.core.interfaces.DocumentPerformer; import com.codio.collab.core.types.DocumentMessage; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.QueueingConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class DocumentRequestPerformer implements Runnable, DocumentPerformer { private static final Logger LOG = LoggerFactory.getLogger(DocumentRequestPerformer.class); private QueueingConsumer consumer; private BackendProcessor backendProcessor; private boolean isStopped = false; private Channel channel; public DocumentRequestPerformer(final Connection connection, final String name, final BackendProcessor backendProcessor) { this.backendProcessor = backendProcessor; try { channel = connection.createChannel(); channel.basicQos(1); consumer = new QueueingConsumer(channel); channel.basicConsume(name, false, consumer); } catch (IOException e) { LOG.error("Problem with init document consumer = {}, {}", e.getMessage(), e); } } @Override public void run() { while (!isStopped()) { try { QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000); if (delivery == null) { continue; } long tag = delivery.getEnvelope().getDeliveryTag(); try { final String msg = new String(delivery.getBody()); LOG.debug("Process message = {}", msg); DocumentMessage message = Context.getMapper().readValue(msg.getBytes(), DocumentMessage.class); backendProcessor.processDocumentMessage(message, tag, this); } catch (Exception ex) { channel.basicAck(tag, false); } } catch (Exception e) { LOG.error("Error in rmq process = {}, {}, {}", e.getMessage(), e.getStackTrace(), e); } } } public void ackDocumentMessage(final long tag) { try { channel.basicAck(tag, false); } catch (IOException e) { LOG.error("ack problem {}", e); } } public boolean isStopped() { return isStopped; } public void setStopped(boolean isStopped) { this.isStopped = isStopped; } }