أساسيات الاتصال بين الخدمات
استكشف أنماط الاتصال المتزامن، مثل استدعاءات REST بين الخدمات المصغّرة.
أساسيات الاتصال بين الخدمات درس مجاني في Spring Boot 4 Microservices & REST APIs على CoddyKit. هذا هو الدرس 2 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Microservices & REST APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Talking Between Services
Microservices are small, independent services. For them to work together, they need to communicate! Imagine an Order Service needing product details from a Product Service.
This lesson explores how services talk to each other. We'll focus on synchronous communication, where one service waits for a reply from another.
Sync or Async?
Communication between services can be:
- Synchronous: The calling service sends a request and waits for a response before continuing its own task. Think of a phone call.
- Asynchronous: The calling service sends a request and doesn't wait for an immediate response. It continues its work. Think of sending an email.
Today, we'll dive into synchronous communication, often done using REST APIs.
RESTful Service Calls
REST (Representational State Transfer) is a popular architectural style for web services. It's also perfect for microservices to communicate.
Services expose endpoints, and others consume them using standard HTTP methods like GET, POST, PUT, and DELETE.
It's like one service acting as a client and another as a server, just like your browser talks to a website.
How Services Connect
When Service A needs data from Service B, Service A acts as an HTTP client. It constructs an HTTP request (method, URL, headers, body) and sends it to Service B.
Service B, acting as an HTTP server, processes the request and sends back an HTTP response (status code, headers, body).
This is a fundamental pattern in microservice architectures.
Our Target Service Example
To demonstrate, let's imagine a simple "Product Service" that our "Order Service" will call. This service will have both GET and POST endpoints.
This code snippet shows a basic Spring Boot controller for our Product Service, running on port 8081. It simulates product retrieval and creation.
package com.example.productservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@SpringBootApplication
@RestController
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
@GetMapping("/products/{id}")
public String getProductInfo(@PathVariable String id) {
return "Product " + id + " Details (from Product Service)";
}
@PostMapping("/products")
public String createProduct(@RequestBody Map<String, String> productData) {
String name = productData.getOrDefault("name", "Unknown");
String price = productData.getOrDefault("price", "0.00");
return "Created Product: " + name + " with price " + price + " (via Product Service)";
}
}Calling with RestTemplate (GET)
Spring's RestTemplate is a synchronous client for making HTTP requests. It's a classic way to call other REST services.
Here's how our "Order Service" could use RestTemplate to get product info from our Product Service:
package com.example.orderservice;
import org.springframework.web.client.RestTemplate;
public class OrderServiceCaller {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String productId = "123";
String url = "http://localhost:8081/products/" + productId; // Product Service URL
System.out.println("Calling Product Service for ID: " + productId);
try {
String result = restTemplate.getForObject(url, String.class);
System.out.println("Received: " + result);
} catch (Exception e) {
System.out.println("Error calling Product Service: " + e.getMessage());
}
}
}Processing the Response
When RestTemplate makes a call, it expects a response. The getForObject() method automatically converts the response body into the specified Java type (here, String.class).
For more control, you can use getForEntity() which returns a ResponseEntity object. This gives you access to:
- Status Code: E.g., 200 OK, 404 Not Found.
- Headers: E.g., Content-Type.
- Body: The actual data.
Sending Data with POST
Often, services need to send data to each other, not just request it. This is where POST requests come in.
RestTemplate provides methods like postForObject() or postForEntity() to send data in the request body.
Let's see how our "Order Service" could create a new product:
package com.example.orderservice;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
public class OrderServicePostCaller {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8081/products"; // Product Service POST URL
// Data to send in the request body
Map<String, String> productData = new HashMap<>();
productData.put("name", "New Gadget");
productData.put("price", "99.99");
System.out.println("Calling Product Service to create product...");
try {
// postForObject sends data and expects a response object
String result = restTemplate.postForObject(url, productData, String.class);
System.out.println("Received: " + result);
} catch (Exception e) {
System.out.println("Error calling Product Service POST: " + e.getMessage());
}
}
}Handling Communication Errors
What happens if the target service is down, or sends an error?
RestTemplate will throw exceptions for certain HTTP status codes (e.g., 4xx client errors, 5xx server errors) or connection issues.
It's crucial to wrap your service calls in try-catch blocks to gracefully handle these failures. You might log the error, return a default value, or inform the user.
Later lessons will cover more advanced resilience patterns like Circuit Breakers.
Quick Check: Communication
Consider a microservice architecture where an OrderService needs to fetch real-time stock availability from a WarehouseService before confirming an order.
Recap: Inter-Service Talk
In this lesson, we explored the basics of synchronous inter-service communication in a microservices architecture.
- We learned that services often communicate using REST APIs and standard HTTP methods.
RestTemplateis a powerful Spring Boot tool for making these synchronous calls.- It's important to handle responses and errors gracefully.
Next, we'll look at more advanced communication patterns!
الأسئلة الشائعة
هل درس «أساسيات الاتصال بين الخدمات» مجاني؟
نعم — نص درس «أساسيات الاتصال بين الخدمات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Microservices & REST APIs، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Microservices & REST APIs 3 دروس في المجموع.
ماذا ستتعلم في «أساسيات الاتصال بين الخدمات»؟
استكشف أنماط الاتصال المتزامن، مثل استدعاءات REST بين الخدمات المصغّرة. تتمرن على Spring Boot 4 Microservices & REST APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Microservices & REST APIs؟
لا تُشترط خبرة سابقة. Spring Boot 4 Microservices & REST APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 3.
كم من الوقت يستغرق درس «أساسيات الاتصال بين الخدمات»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Microservices & REST APIs هذا؟
نعم. كل درس في Spring Boot 4 Microservices & REST APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تفكيك التطبيقات الأحادية إلى خدمات مصغّرة
- أساسيات الاتصال بين الخدمات
- نظرة عامة على البنى المعتمدة على الأحداث