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.FrontendProcessor; import com.codio.collab.core.types.AskMessage; 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; import java.util.UUID; /** * Created by destitutus on 20.07.14. */ public class DocumentResponsePerformer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(DocumentResponsePerformer.class); private QueueingConsumer consumer; private FrontendProcessor frontendProcessor; private boolean isStopped = false; private Channel channel; public DocumentResponsePerformer(final Connection connection, final String name, final FrontendProcessor frontendProcessor) { this.frontendProcessor = frontendProcessor; try { LOG.debug("DocumentResponsePerformer"); channel = connection.createChannel(); channel.basicQos(1); consumer = new QueueingConsumer(channel); channel.basicConsume(name, false, consumer); } catch (IOException e) { LOG.error("Problem with init response 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); AskMessage message = Context.getMapper().readValue(msg.getBytes(), AskMessage.class); frontendProcessor.processDocumentMessage(message); } finally { channel.basicAck(tag, false); } } catch (Exception e) { LOG.error("Error in rmq process = {}, {}, {}", e.getMessage(), e.getStackTrace(), e); } } } public boolean isStopped() { return isStopped; } public void setStopped(boolean isStopped) { this.isStopped = isStopped; } }