【问题标题】:Send notifications with Rabbitmq使用 Rabbitmq 发送通知
【发布时间】:2016-03-29 07:14:53
【问题描述】:

我正在使用 django、django rest 框架和 Rabbitmq,我想要的是在用户创建评论(如长轮询)后使用 Rabbitmq 向客户端发送通知。 我在这里关注RabbitMQ Tutorials

这是我创建 cmets 的 view.py:

class CommentList(generics.ListCreateAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def create(self, request, *args, **kwargs):
        #use pika and rabbitmq to notifity user
        connection = pika.BlockingConnection(pika.ConnectionParameters(
                host='localhost'))
        channel = connection.channel()
        channel.queue_declare(queue='task_queue', durable=True)
        message = 'Hello, world'
        channel.basic_publish(exchange='',
                              routing_key='task_queue',
                              body=message,
                              properties=pika.BasicProperties(
                                 delivery_mode = 2, # make message persistent
                              ))
        connection.close()        
        return super().create(request, args, kwargs)

我创建了一个队列调用“task_queue”,并在每次创建评论时发送消息“Hello, world”。

这是我的 view.py 来接收消息:

def get_notifications(request):
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='task_queue', durable=True)

    def callback(ch, method, properties, body):
        return HttpResponse("ok")
        ch.basic_ack(delivery_tag = method.delivery_tag)

    #channel.basic_qos(prefetch_count=1)
    channel.basic_consume(callback,
                      queue='task_queue')

    channel.start_consuming()

在客户端,我使用 jquery ajax 函数来请求数据:

function poll() {
    var poll_interval=0;

    $.ajax({
        url: "/sub", //sub calls get_notifications()
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            append_circle();
            poll_interval=0;
        },
        error: function () {
            poll_interval=1000;
        },
        complete: function () {
            setTimeout(poll, poll_interval);
        },
    });
}

我可以在创建评论后发送消息,但是我的客户端没有收到任何数据,在我的 chrome 控制台中,我发现:

sub/    (pending)   xhr

我该怎么办?

【问题讨论】:

  • 这并不是 rabbitmq 的真正用途。
  • 所以我应该改用 django-socketio 或 django 频道?

标签: django rabbitmq django-rest-framework long-polling


【解决方案1】:

对于这种类型的应用程序,websockets 是更好的选择。我建议您使用 websockets 而不是长轮询。因为长轮询是资源匮乏的过程。要使用 websockets,可以使用channels

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多