0
我正在使用django,Django rest框架和Rabbitmq,我想要的是在用戶創建評論(如長輪詢)後使用Rabbitmq向客戶端發送通知。 我在此處關注RabbitMQ Tutorials。發送有關Rabbitmq的通知
這是我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」,併發送消息「你好,世界」每次我創建時間我的評論。
這是我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頻道嗎? – Windsooon