简体   繁体   English

django rest框架中两个或多个微服务如何通信?

[英]How to communicate two or more microservices in django rest framework?

I have been looking to communicate two or multiple microservices in django and need to make them communicate with each.我一直在寻找 django 中两个或多个微服务的通信,需要让它们相互通信。 I've reasearched about it and didnt get proper info about it.我已经重新搜索过它,但没有得到关于它的正确信息。 what i understood is each microservices application completely dont depend on one another including the database.我的理解是每个微服务应用程序都完全不依赖于彼此,包括数据库。 Now how to communicate each microservices with one another.现在如何让每个微服务相互通信。 there are 2 methods **synchronous and asynchronous ** method.有两种方法**同步和异步**方法。

i dont want to use synchronous.我不想使用同步。 how to communicate the endpoints of api in asynchronous way?如何以异步方式通信 api 的端点? i found some message brokers like rabbitMQ, kafka, gRPc... Which is the best brokers.我发现了一些消息代理,例如 rabbitMQ、kafka、gRPc……这是最好的代理。 and how to communicate using those service?以及如何使用这些服务进行通信? i didnt get any proper guidance.我没有得到任何适当的指导。 I'm willing to learn, can anybody please explain with some example?我愿意学习,任何人都可以用一些例子来解释吗? It will be huge boost in my work.这将对我的工作产生巨大的推动作用。

Because you are starting out, I suggest that you go with RabbitMQ. RabbitMQ is easier to set up and use than Apache Kafka.因为你刚起步,我建议你go和RabbitMQ。RabbitMQ比Apache更容易设置和使用Kafka。

Then it depends on what kind of asynchronous communication you are looking for.那么就看你要找什么样的异步通信了。 For example, if you have two microservices;例如,如果您有两个微服务; A and B , and you want A to communicate with B , do you want the microservice B to send a response back to A ? AB ,并且您希望A 与 B 通信,是否希望微服务 B将响应发送回 A Or do you want microservice B just to process some task (like send an email) and don't respond back to A ?或者你想让微服务 B 只处理一些任务(比如发送电子邮件)而不回复 A吗?

Here is a simple example of how to use RabbitMQ in your Django project to process some tasks:下面是一个简单的例子,说明如何在你的 Django 项目中使用 RabbitMQ 来处理一些任务:

First, you will need to install django-rabbitmq package to help you communicate with the RabbitMQ broker on both the microservices, sender and reciever:首先,您需要安装django-rabbitmq package 以帮助您在微服务、发送方和接收方上与 RabbitMQ 代理进行通信:

pip install django-rabbitmq

Then add django_rabbitmq to your INSTALLED_APPS setting and create a RABBITMQ_CONFIG dictionary in your Django settings file with the connection details for your RabbitMQ server on both the microservices:然后将django_rabbitmq添加到您的INSTALLED_APPS 设置中,并在您的 Django 设置文件中创建一个RABBITMQ_CONFIG字典,其中包含两个微服务上 RabbitMQ 服务器的连接详细信息:

RABBITMQ_CONFIG = {
    'default': {
        'host': 'localhost',
        'port': 5672,
        'user': 'guest',
        'password': 'guest',
    },
}

Finally, in microservice A, use the django_rabbitmq.publishers.Publisher class to publish messages to RabbitMQ:最后,在微服务A中,使用django_rabbitmq.publishers.Publisher class向RabbitMQ发布消息:

from django.shortcuts import render
from django_rabbitmq import publishers

def send_message(request):
    # Connect to RabbitMQ and declare a queue
    publisher = publishers.Publisher(queue_name='my_queue')

    # Send a message
    publisher.send_message('Hello World!')

    return render(request, 'send_message.html', {})

And create a management command in microservice B to consume messages from the queue.并在微服务 B 中创建一个管理命令来消费队列中的消息。 You can do this by creating a file management/commands/consume_messages.py with the following code:您可以通过使用以下代码创建文件management/commands/consume_messages.py来完成此操作:

from django.core.management.base import BaseCommand
from django_rabbitmq import consumers

class Command(BaseCommand):
    help = 'Consumes messages from the specified queue'

    def add_arguments(self, parser):
        parser.add_argument('queue_name', type=str, help='The name of the queue to consume messages from')

    def handle(self, *args, **options):
        queue_name = options['queue_name']

        # Define a callback function to process the received message
        def callback(ch, method, properties, body):
            print(" [x] Received %r" % body)

        # Create a message consumer and start consuming messages from the queue
        consumer = consumers.Consumer(queue_name, callback)
        consumer.start_consuming()

Don't forget to start the command to actually start processing tasks from the RabbitMQ:不要忘记启动命令以实际开始处理来自 RabbitMQ 的任务:

python manage.py consume_messages my_queue

You can check out RabbitMQ Getting Started Page to get started using RabbitMQ. And you can find more information and examples in the django-rabbitmq documentation .您可以查看RabbitMQ 入门页面以开始使用 RabbitMQ。您可以在django-rabbitmq 文档中找到更多信息和示例。

There are a few different ways to communicate between microservices in a Django Rest Framework (DRF) application. Django Rest 框架 (DRF) 应用程序中的微服务之间有几种不同的通信方式。 Here are a few options:这里有几个选项:

Use HTTP requests: One option is to use HTTP requests to send data between microservices.使用 HTTP 请求:一种选择是使用 HTTP 请求在微服务之间发送数据。 This can be done using the requests library in Python or using JavaScript's fetch API in the frontend.这可以使用 Python 中的请求库或在前端使用 JavaScript 的 fetch API 来完成。

Use a message queue: Another option is to use a message queue, such as RabbitMQ or Kafka, to send messages between microservices.使用消息队列:另一种选择是使用消息队列,例如 RabbitMQ 或 Kafka,在微服务之间发送消息。 This can be useful if you need to decouple the services and handle asynchronous communication.如果您需要解耦服务并处理异步通信,这会很有用。

Use a database: You can also use a database, such as PostgreSQL or MongoDB, to store data that is shared between microservices.使用数据库:您还可以使用数据库(例如 PostgreSQL 或 MongoDB)来存储微服务之间共享的数据。 This can be done using Django's ORM or a database driver in your preferred language.这可以使用 Django 的 ORM 或您首选语言的数据库驱动程序来完成。

Which method you choose will depend on your specific requirements and the nature of the communication between your microservices.您选择哪种方法取决于您的具体要求和微服务之间通信的性质。

Here is a list of different approaches you can use to communicate to microservices: https://gotopaisa.com/how-to-communicate-two-or-more-microservices-in-django-python/以下是可用于与微服务通信的不同方法的列表: https://gotopaisa.com/how-to-communicate-two-or-more-microservices-in-django-python/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django REST Framework:如何组合两个查询集? - Django REST Framework: How to combine two querysets? 如何在django rest框架中将多个变量传递给modelViewSet? - How to pass more than one variables to modelViewSet in django rest framework? 如何在 Django Rest 框架中记录 400 个响应的更多详细信息? - How to log more detail of 400 responses in Django Rest Framework? 如何在 django rest 框架中向返回响应添加更多字段 - How to add more fields to the return response in django rest framework 如何组合来自两个模型的两个查询集? Django Rest 框架 - How to combine two querysets from two models? Django Rest Framework Django Rest Framework中相同资源的两个端点 - Two endpoints for the same resource in django rest framework Django Rest 框架:一个路由器的两个视图集 - Django Rest Framework: two viewsets for one router 如何在Django Rest框架的通用API视图中访问url kwargs(更具体地讲ListCreateAPIView)? - How to access url kwargs in generic API views (ListCreateAPIView to be more specific) in django rest framework? 在Django Rest Framework中列出某些内容时,如何不仅显示对象的外键? - How can you show more than just the foreign key of an object when listing something in Django Rest Framework? Django - 如何使用 Django Rest 框架按日期过滤? - Django - How to filter by date with Django Rest Framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM