java - 从 Java 与 Django/Celery 互操作

标签 java python django rabbitmq celery

我们公司有一个基于 Python 的网站和一些基于 Python 的工作节点,它们通过 Django/Celery 和 RabbitMQ 进行通信。我有一个基于 Java 的应用程序,需要将任务提交给基于 Celery 的工作人员。我可以很好地将工作从 Java 发送到 RabbitMQ,但是基于 Celery 的工作人员永远不会接手这些工作。通过查看两种类型的作业提交的数据包捕获,存在差异,但我无法理解如何解释它们,因为很多都是二进制的,我找不到有关解码的文档。这里有人对 Java/RabbitMQ 和 Celery 协同工作有任何引用或经验吗?

最佳答案

我找到了解决方案。 RabbitMQ 的 Java 库指的是交换器/队列/路由键。在 Celery 中,队列名称实际上映射到 Java 库中引用的交换器。默认情况下,Celery 的队列就是“celery”。如果您的 Django 设置使用以下语法定义了一个名为“myqueue”的队列:

CELERY_ROUTES = {
    'mypackage.myclass.runworker'      : {'queue':'myqueue'},
}

然后基于 Java 的代码需要执行如下操作:

        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = null ;
        try {
            connection = factory.newConnection(mqHost, mqPort);
        } catch (IOException ioe) {
            log.error("Unable to create new MQ connection from factory.", ioe) ;
        }

        Channel channel = null ;
        try {
            channel = connection.createChannel();
        } catch (IOException ioe) {
            log.error("Unable to create new channel for MQ connection.", ioe) ;
        }

        try {
            channel.queueDeclare("celery", false, false, false, true, null);
        } catch (IOException ioe) {
            log.error("Unable to declare queue for MQ channel.", ioe) ;
        }

        try {
            channel.exchangeDeclare("myqueue", "direct") ;
        } catch (IOException ioe) {
            log.error("Unable to declare exchange for MQ channel.", ioe) ;
        }

        try {
            channel.queueBind("celery", "myqueue", "myqueue") ;
        } catch (IOException ioe) {
            log.error("Unable to bind queue for channel.", ioe) ;
        }

            // Generate the message body as a string here.

        try {
            channel.basicPublish(mqExchange, mqRouteKey, 
                new AMQP.BasicProperties("application/json", "ASCII", null, null, null, null, null, null, null, null, null, "guest", null, null),
                messageBody.getBytes("ASCII"));
        } catch (IOException ioe) {
            log.error("IOException encountered while trying to publish task via MQ.", ioe) ;
        }

事实证明,这只是术语上的差异。

关于java - 从 Java 与 Django/Celery 互操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6933833/

相关文章:

python - 谷歌应用程序引擎(Python): Using multiple forms on a single web page

python - Django 3.1.3 中的电子邮件激活链接问题

java - 通过分割字符串从另一个字符串数组列表创建一个字符串数组列表

python - Matplotlib 条形图 x Axis 下方的负值

java - 实体数据类型必须与 JPA 存储库中的参数相同吗?

Python 类型错误 : 'NoneType' object has no attribute '__getitem__' for Google Search

python - 使用 django-allauth 启用 oauth 登录,但使用自定义提供程序

python - Debug = True 时 Django 错误报告电子邮件

java - org.hibernate.exception.JDBCConnectionException : Unable to open JDBC Connection for DDL execution

java - 当更多的对象意味着更多的实现时间时,为什么人们鼓励在 java 中使用更多的类?