芹菜来管理java任务

时间:2016-03-02 05:16:00

标签: java python rabbitmq celery

我有一个使用rabbitmq与celery通信的java客户端,并将任务发送到芹菜服务器以添加2个数字 x y

String QUEUE_NAME = "celery";
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
String x = "5";
String y = "10";
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
String ID = UUID.randomUUID().toString();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
String message = "{\"id\":\""+ID+"\", \"task\": \"tasks.add\", \"args\": ["+x+","+y+"], \"kwargs\": {}, \"retries\": 0, \"eta\": \"2009-11-17T12:30:56.527191\"}";
channel.basicPublish("", QUEUE_NAME, new AMQP.BasicProperties.Builder()
        .contentType("application/json").contentEncoding("utf-8")
        .build(), message.getBytes("utf-8"));
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();

我们有一个python api add来添加这些数字,由celery管理。

from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y

我想在java中编写这个add(x,y)函数,以便以某种方式识别java add(x,y) method并管理它。

注意:我正在寻找没有webhooks的解决方案。

提前致谢。

2 个答案:

答案 0 :(得分:0)

查看https://crabhi.github.io/celery-java/

对于JVM,Celery客户端和工作人员的实施(目前非常阿尔法)。

您可以注释您的任务类:

 import org.sedlakovi.celery.Task;

 @Task
 public class TestTask {

     public int sum(int x, int y) {
         return x + y;
     }
 }

然后像这样调用任务:

Client client = new Client(rabbitConnectionChannel, rabbitBackend);

Integer result = TestTaskProxy.with(client).sum(1, 7).get();

答案 1 :(得分:0)

import json

from celery import Celery
from celery import bootsteps
from kombu import Consumer, Exchange, Queue

queue = Queue("input.queue", Exchange("default"), "input.key")

app = Celery(broker="amqp://")


# Decalring the general input message handler
class InputMessageHandler(object):
    def handle(self, body):
        body_json = json.loads(body)
        _type = body_json["type"]
        if _type == "ETL":
            ETLMessageHandler().handle(body_json)


# Declaring the ETL message handler
class ETLMessageHandler(object):
    def handle(self, body):
        print("Working on ETL for message: {0}".format(body))
        # Calling out your Celery tasks here


# Declaring the bootstep for our purposes
class InputMessageConsumerStep(bootsteps.ConsumerStep):
    def get_consumers(self, channel):
        return [Consumer(channel,
                         queues=[queue],
                         callbacks=[self.handle_message],
                         accept=["json"])]

    def handle_message(self, body, message):
        InputMessageHandler().handle(body)
        message.ack()


app.steps["consumer"].add(InputMessageConsumerStep)


if __name__ == "__main__":
    app.start()

enter image description here

enter image description here