การส่งข้อมูลเมตาแบบกำหนดเอง
ค้นพบวิธีส่งและรับคู่คีย์-ค่าแบบกำหนดเองเป็นข้อมูลเมตาพร้อมคำขอและการตอบกลับ gRPC
การส่งข้อมูลเมตาแบบกำหนดเอง เป็นบทเรียน gRPC & High Performance APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน gRPC & High Performance APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส gRPC & High Performance APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is gRPC Metadata?
In gRPC, metadata refers to key-value pairs that are attached to an RPC call, similar to HTTP headers.
Unlike the main message payload, metadata carries information about the call itself, rather than the application data being transmitted.
- It's for auxiliary data.
- It travels with requests and responses.
- It's separate from your protobuf messages.
Why Use Metadata?
Metadata is incredibly useful for carrying information that doesn't belong in your service's primary request or response messages.
Common use cases include:
- Authentication Tokens: Sending JWTs or API keys.
- Tracing IDs: Propagating unique request IDs for distributed tracing.
- Custom Headers: Any other contextual information needed by your services.
Metadata Structure & Types
Metadata consists of a list of key-value pairs.
- Keys: Are case-insensitive ASCII strings.
- Values: Can be either ASCII strings or binary data.
For binary values, the key must end with -bin (e.g., auth-token-bin). gRPC handles the encoding for these.
Client: Sending Request Metadata
Clients attach metadata to outgoing requests using the gRPC Metadata class. This object is then added to the gRPC call stub.
You create Metadata.Key objects to define your header keys and their marshallers (how they are converted to/from strings or bytes).
Client: Sending Metadata Example
This Java client snippet shows how to create a Metadata object and attach it to your stub before making an RPC call. Ensure your `hello.proto` is compiled.
package com.coddykit.grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.stub.MetadataUtils;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
public class GrpcClient {
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public GrpcClient(String host, int port) {
this.channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void sayHello(String name, String customValue) {
System.out.println("Sending custom-key: " + customValue);
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
// 1. Create Metadata object
Metadata headers = new Metadata();
// 2. Define a Metadata.Key for your header
Metadata.Key<String> customKey = Metadata.Key.of(
"custom-key", Metadata.ASCII_STRING_MARSHALLER);
// 3. Put the key-value pair into Metadata
headers.put(customKey, customValue);
// 4. Attach metadata to the stub
GreeterGrpc.GreeterBlockingStub stubWithMetadata =
MetadataUtils.attachHeaders(blockingStub, headers);
try {
HelloReply response = stubWithMetadata.SayHello(request);
System.out.println("Greeting: " + response.getMessage());
} catch (StatusRuntimeException e) {
System.err.println("RPC failed: " + e.getStatus());
}
}
public static void main(String[] args) throws Exception {
GrpcClient client = new GrpcClient("localhost", 50051);
try {
client.sayHello("CoddyKit User", "my-session-id-123");
} finally {
client.shutdown();
}
}
}Server: Receiving Request Metadata
On the server side, incoming metadata is typically accessed using a ServerInterceptor.
An interceptor sits between the gRPC runtime and your service implementation, allowing you to inspect and modify calls.
- It receives a
Metadataobject. - You can extract values using
Metadata.Key. - Often, metadata is then added to the
Contextfor easy access within service methods.
Server: Receiving Metadata Example
This Java server example shows a ServerInterceptor extracting a custom header and making it available to the service via Context. Ensure your `hello.proto` is compiled.
package com.coddykit.grpc;
import io.grpc.Context;
import io.grpc.Metadata;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
public class GrpcServer {
private Server server;
// Context.Key to store the custom value for the service method
private static final Context.Key<String> CUSTOM_VALUE_CTX_KEY = Context.key("custom-value");
private void start() throws IOException {
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(new GreeterService())
.intercept(new CustomHeaderInterceptor()) // Add our interceptor
.build()
.start();
System.out.println("Server started, listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.err.println("*** shutting down server");
try { GrpcServer.this.stop(); }
catch (InterruptedException e) { e.printStackTrace(System.err); }
System.err.println("*** server shut down");
}));
}
private void stop() throws InterruptedException {
if (server != null) { server.shutdown().awaitTermination(); }
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) { server.awaitTermination(); }
}
public static void main(String[] args) throws Exception {
final GrpcServer server = new GrpcServer();
server.start();
server.blockUntilShutdown();
}
static class GreeterService extends GreeterGrpc.GreeterImplBase {
@Override
public void SayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
// Retrieve custom value from Context
String customValue = CUSTOM_VALUE_CTX_KEY.get();
System.out.println("Service received custom-key: " + customValue);
HelloReply reply = HelloReply.newBuilder()
.setMessage("Hello " + request.getName() +
"! Custom value: " + customValue)
.build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
static class CustomHeaderInterceptor implements ServerInterceptor {
// Define the Metadata.Key for our custom header
private static final Metadata.Key<String> CUSTOM_KEY =
Metadata.Key.of("custom-key", Metadata.ASCII_STRING_MARSHALLER);
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
// Get the custom value from incoming headers
String customValue = headers.get(CUSTOM_KEY);
System.out.println("Interceptor received custom-key: " + customValue);
// Store the custom value in the Context for the service to access
Context context = Context.current().withValue(CUSTOM_VALUE_CTX_KEY, customValue);
// Proceed with the call within the new context
return Context.current().call(() -> next.startCall(call, headers));
}
}
}Server: Sending Response Metadata
Servers can also send metadata back to clients, either as response headers or response trailers.
- Response Headers: Sent before any response messages. Use
ServerCall.sendHeaders(Metadata). - Response Trailers: Sent at the end of the RPC, after all response messages. Often used for status or final context.
Both are handled within the ServerCall object, which is available in interceptors or advanced service implementations.
Client: Receiving Response Metadata
Clients can access the response metadata (headers and trailers) through the ClientCall.Listener interface, typically used with asynchronous (non-blocking) stubs.
The listener provides callbacks like onHeaders(Metadata) and onTrailers(Metadata) where you can inspect the incoming metadata.
Metadata Use Cases
Which of the following is NOT a typical use case for gRPC metadata?
Recap: Metadata in gRPC
You've learned how gRPC metadata acts like HTTP headers, carrying essential non-application data alongside your RPC calls.
- Clients send metadata with requests.
- Servers receive and process request metadata (often via interceptors).
- Servers can send response metadata (headers/trailers) back to clients.
- Metadata is crucial for cross-cutting concerns like authentication and tracing.
Mastering metadata allows for more robust and observable gRPC services!
เรียนรู้ gRPC & High Performance APIs ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “การส่งข้อมูลเมตาแบบกำหนดเอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การส่งข้อมูลเมตาแบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส gRPC & High Performance APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส gRPC & High Performance APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การส่งข้อมูลเมตาแบบกำหนดเอง”
ค้นพบวิธีส่งและรับคู่คีย์-ค่าแบบกำหนดเองเป็นข้อมูลเมตาพร้อมคำขอและการตอบกลับ gRPC คุณปฏิบัติ gRPC & High Performance APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน gRPC & High Performance APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน gRPC & High Performance APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การส่งข้อมูลเมตาแบบกำหนดเอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน gRPC & High Performance APIs นี้ได้ไหม
ได้ บทเรียน gRPC & High Performance APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รหัสสถานะและการจัดการข้อผิดพลาด
- การส่งข้อมูลเมตาแบบกำหนดเอง
- บริบทและกำหนดเวลา
- รูปแบบข้อผิดพลาดแบบละเอียดด้วย google.rpc.Status