0Pricing
FastAPI Backend Development Bootcamp · 课时

服务间通信

为 FastAPI 微服务之间的通信实现各种模式,例如 HTTP 或消息队列。

服务间通信 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Services Talk

In a microservices architecture, your application isn't one big program. Instead, it's many smaller, independent services working together. For these services to achieve a common goal, they need to communicate with each other.

Imagine an e-commerce system: one service handles user accounts, another manages product inventory, and a third processes orders. When a user places an order, the order service needs to talk to the inventory service to check stock and the user service to get payment details.

HTTP: Direct Conversations

The most common way for microservices to communicate is through HTTP requests. This is like one service directly calling another service's API endpoint.

  • Synchronous: The calling service waits for a response before continuing.
  • Simple: Easy to understand and implement, especially for request-response patterns.
  • Familiar: Uses the same HTTP protocol you're already familiar with for web browsing.

FastAPI services naturally expose HTTP endpoints, making this a straightforward method.

Making an HTTP Request

In Python, the requests library is excellent for making HTTP calls. Here's how one FastAPI service might call another to get user data.

Assume Service B exposes a /users/{user_id} endpoint, and Service A calls it:

import requests

def get_user_from_service_b(user_id: int):
    # In a real scenario, 'service_b_url' would be a config variable
    service_b_url = f"http://localhost:8001/users/{user_id}"
    try:
        response = requests.get(service_b_url)
        response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error calling Service B: {e}")
        return None

if __name__ == "__main__":
    print("Simulating a call to Service B for user 1...")
    user_data = get_user_from_service_b(1)
    if user_data:
        print(f"Received user data: {user_data}")
    else:
        print("Failed to get user data.")
    print("\nNote: For this to truly work, a service B needs to be running at http://localhost:8001.")

Handling HTTP Responses

After making an HTTP request, it's crucial to handle the response properly. This includes checking the HTTP status code and parsing the response body.

  • Status Codes: 200 OK means success, 404 Not Found means the resource wasn't there, 500 Internal Server Error indicates a problem on the server side.
  • Response Body: Often contains data in JSON format, which you can parse using response.json().
  • Error Handling: Always wrap your requests in try-except blocks to catch network issues or server errors.

Resilient HTTP: Timeouts & Retries

Network issues or slow services can cause your HTTP calls to hang or fail. Building resilience into your communication is vital.

  • Timeouts: Set a maximum duration to wait for a response. If the service doesn't respond within this time, the request fails, preventing your service from hanging indefinitely.
  • Retries: If a request fails due to a transient error (e.g., network glitch, temporary service overload), you can automatically retry the request a few times with a delay. Libraries like tenacity can help implement this easily.

These strategies improve the robustness of your microservices.

Message Queues: Decoupling Services

Sometimes, direct HTTP calls aren't the best fit. For tasks that don't require an immediate response, or when you want to reduce direct dependencies between services, message queues are powerful.

A message queue acts as an intermediary, storing messages until a consumer service is ready to process them. Popular examples include RabbitMQ and Apache Kafka.

  • Asynchronous: The sender (producer) doesn't wait for the receiver (consumer) to process the message.
  • Decoupled: Services don't need to know about each other's direct network locations.
  • Scalable: Easily handle spikes in load by adding more consumers.

The Producer-Consumer Model

Message queues operate on a simple principle:

  • Producer: A service that creates and sends messages to a queue. It "fires and forgets" the message.
  • Queue: A temporary storage buffer that holds messages until they are processed.
  • Consumer: A service that listens to a queue, retrieves messages, and processes them.

This model allows for robust, scalable, and fault-tolerant communication, especially for background tasks or event-driven architectures.

Conceptual Message Producer

While a full, runnable message queue example is complex, here's a conceptual Python function illustrating how a service might "send" a message to a queue. In reality, this would involve a client library like pika (for RabbitMQ) or confluent-kafka.

Notice that the sender doesn't wait for the message to be processed; it just places it in the queue.

import json
import time

# This is a simplified, conceptual representation.
# In a real app, 'queue_client' would be an actual library client.

class MockQueueClient:
    def publish(self, queue_name: str, message: dict):
        print(f"[{time.time():.2f}] PRODUCER: Sending message to '{queue_name}'...")
        print(f"  Message content: {json.dumps(message)}")
        # In a real scenario, this would send to a message broker
        print("  (Message sent to broker, producer continues its work)")

def send_new_order_event(order_details: dict):
    queue_client = MockQueueClient()
    queue_client.publish("order_processing_queue", order_details)
    print("PRODUCER: Order event sent successfully.")

if __name__ == "__main__":
    order_info = {"order_id": "ORD001", "item": "Laptop", "quantity": 1}
    send_new_order_event(order_info)
    print("\nPRODUCER: Service continues other tasks while order processes.")

When to Choose HTTP

HTTP communication is generally preferred for:

  • Synchronous Requests: When the calling service needs an immediate response to continue its workflow (e.g., getting user profile data, checking inventory before confirming an order).
  • Request-Response Patterns: Simple queries, data retrieval, or operations where the client expects a direct result.
  • Tight Coupling is Acceptable: When services are designed to work closely together and direct calls are efficient.
  • Real-time User Interactions: Often used for front-end to back-end communication, or when an immediate UI update is needed.

Choosing the Right Tool

You've seen two primary ways services communicate. Each has its strengths. Consider the scenario:

A user submits a complex report generation request that might take several minutes to complete. The user doesn't need to wait for it, but wants to be notified when it's done.

Which communication pattern is best suited for the initial request submission?

Recap: Talking Services

Great job! You've explored the fundamental ways microservices communicate.

  • HTTP: Best for synchronous, request-response interactions where immediate feedback is needed. It's direct and easy to implement using libraries like requests.
  • Message Queues: Ideal for asynchronous, decoupled communication, handling long-running tasks, and enabling event-driven architectures. They use a producer-consumer model for robust message delivery.

Choosing the right pattern depends on your specific needs for coupling, latency, and reliability. In the next lesson, we'll dive into building an API Gateway!

常见问题解答

「服务间通信」课时是免费的吗?

是的 — 「服务间通信」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「服务间通信」这节课中我会学到什么?

为 FastAPI 微服务之间的通信实现各种模式,例如 HTTP 或消息队列。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「服务间通信」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设计微服务架构
  2. 服务间通信
  3. 使用 FastAPI 实现 API 网关
  4. 服务发现与健康检查
← 返回 FastAPI Backend Development Bootcamp