GraphQL APIs with Spring Boot · درس

DataLoaders مع سياق Spring والعمليات غير المتزامنة

ادمج GraphQL DataLoaders بسلاسة في Spring Boot: سجّلها لكل طلب، واستدعها في المحللات، وادمجها مع الوصول غير المتزامن وغير الحاجب للبيانات.

الدرس 4 من 413 خطوة

DataLoaders مع سياق Spring والعمليات غير المتزامنة درس مجاني في GraphQL APIs with Spring Boot على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في GraphQL APIs with Spring Boot، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة GraphQL APIs with Spring Boot 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Recap: Why DataLoaders

You already know DataLoaders batch and cache to defeat the N+1 problem. Now the focus shifts to integration: wiring them into Spring's request lifecycle and async model the right way.

DataLoaders Are Request-Scoped

A DataLoader's cache must not leak across requests, or one user could see another's stale data. DataLoaders therefore live for a single GraphQL request and are discarded afterward.

Registering with DataLoaderRegistry

Spring for GraphQL builds a fresh DataLoaderRegistry per request. You contribute loaders to it using a BatchLoaderRegistry bean.

@Configuration
public class LoaderConfig {
    public LoaderConfig(BatchLoaderRegistry registry,
                        AuthorService authors) {
        registry.forTypePair(Long.class, Author.class)
            .registerMappedBatchLoader((ids, env) ->
                Mono.fromCallable(() -> authors.findByIds(ids)));
    }
}

Mapped vs Plain Batch Loaders

A mapped batch loader returns a Map of key to value, which is ideal when results may come back unordered or with gaps. A plain batch loader returns a list aligned by index.

Accessing a Loader in a Resolver

In a @SchemaMapping method, inject the registered DataLoader directly as a parameter. Spring supplies the request-scoped instance.

@SchemaMapping
public CompletableFuture<Author> author(Book book,
        DataLoader<Long, Author> loader) {
    return loader.load(book.getAuthorId());
}

Why CompletableFuture?

A DataLoader's load() returns a CompletableFuture. The framework collects all such futures in a tick, fires one batch call, then completes them together. Returning the future lets GraphQL defer resolution.

Passing Spring Context

Batch loaders receive a BatchLoaderEnvironment that can carry context, like the authenticated user, so authorization-aware loading works correctly.

registry.forTypePair(Long.class, Book.class)
    .registerMappedBatchLoader((ids, env) -> {
        var ctx = env.getContext();
        return Mono.fromCallable(() -> books.findByIds(ids));
    });

Going Non-Blocking

For reactive stacks, return a Mono or Flux from the batch loader so the data fetch never blocks a thread, maximizing throughput.

registry.forTypePair(Long.class, Author.class)
    .registerMappedBatchLoader((ids, env) ->
        authorRepository.findAllById(ids)
            .collectMap(Author::getId));

Combining Loaders

A resolver can use multiple loaders, and loaders can call other loaders. Because batching happens per tick, even chained loads stay efficient and avoid N+1 cascades.

Common Pitfalls

Watch out for:

  • Sharing a loader across requests (cache leak)
  • Calling .get() on the future and blocking
  • Forgetting to map results by key, causing null mismatches
  • Doing heavy work outside the batch function

Best Practices

Keep loaders clean:

  • Register via BatchLoaderRegistry, never manually per request
  • Prefer mapped loaders for robustness
  • Return reactive types on reactive stacks
  • Pass context for auth-aware batching

Quick Check

Test your DataLoader integration knowledge.

Recap

You integrated DataLoaders into Spring:

  • Register loaders via BatchLoaderRegistry, request-scoped
  • Inject them as resolver parameters
  • load() returns a CompletableFuture for deferred batching
  • Pass context and return reactive types for non-blocking loads

Well-integrated loaders make your API both correct and fast.

البدء مجانًا

تعلم GraphQL APIs with Spring Boot مع معلم ذكاء اصطناعي — مجانًا

اكتب وقم بتشغيل أكوادك الفعلية في المتصفح، واحصل على مساعدة فورية من معلم ذكاء اصطناعي متاح 24/7، واستمر من حيث توقفت على الويب أو في التطبيق.

الدورات
12
الدروس
48

الأسئلة الشائعة

هل درس «DataLoaders مع سياق Spring والعمليات غير المتزامنة» مجاني؟

نعم — نص درس «DataLoaders مع سياق Spring والعمليات غير المتزامنة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة GraphQL APIs with Spring Boot، انتقل إلى CoddyKit PRO. تتضمن دورة GraphQL APIs with Spring Boot 4 دروس في المجموع.

ماذا ستتعلم في «DataLoaders مع سياق Spring والعمليات غير المتزامنة»؟

ادمج GraphQL DataLoaders بسلاسة في Spring Boot: سجّلها لكل طلب، واستدعها في المحللات، وادمجها مع الوصول غير المتزامن وغير الحاجب للبيانات. تتمرن على GraphQL APIs with Spring Boot مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ GraphQL APIs with Spring Boot؟

لا تُشترط خبرة سابقة. GraphQL APIs with Spring Boot على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «DataLoaders مع سياق Spring والعمليات غير المتزامنة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس GraphQL APIs with Spring Boot هذا؟

نعم. كل درس في GraphQL APIs with Spring Boot يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. شرح مشكلة N+1
  2. مقدمة إلى GraphQL DataLoaders
  3. تطبيق التجميع والتخزين المؤقت
  4. DataLoaders مع سياق Spring والعمليات غير المتزامنة
← العودة إلى GraphQL APIs with Spring Boot