All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.geneea.celery.backends.rabbit.RabbitResultConsumer Maven / Gradle / Ivy

Go to download

Java library for interfacing with http://celeryproject.org including code for both task submissions and task execution.

There is a newer version: 1.10.4
Show newest version
package com.geneea.celery.backends.rabbit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.geneea.celery.WorkerException;
import com.geneea.celery.backends.TaskResult;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

class RabbitResultConsumer extends DefaultConsumer implements RabbitBackend.ResultsProvider {

    private final LoadingCache> tasks =
            CacheBuilder
                    .newBuilder()
                    .expireAfterWrite(2, TimeUnit.HOURS)
                    .build(new CacheLoader>() {
                @Override
                public SettableFuture load(@Nonnull String key) {
                    return SettableFuture.create();
                }
            });
    private final ObjectMapper jsonMapper = new ObjectMapper();

    RabbitResultConsumer(Channel channel) {
        super(channel);
    }

    @Override
    public ListenableFuture getResult(String taskId) {
        return tasks.getUnchecked(taskId);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
            throws IOException {

        TaskResult payload = jsonMapper.readValue(body, TaskResult.class);

        SettableFuture future = tasks.getUnchecked(payload.taskId);
        boolean setAccepted;
        if (payload.status == TaskResult.Status.SUCCESS) {
            setAccepted = future.set(payload.result);
        } else {
            @SuppressWarnings("unchecked")
            Map exc = (Map) payload.result;
            setAccepted = future.setException(
                    new WorkerException(exc.get("exc_type"), exc.get("exc_message")));
        }
        assert setAccepted;
    }
}