0Pricing
WebSockets & Real-Time Systems with Spring · บทเรียน

การปรับแต่งตัวแปลงข้อความ

ปรับแต่งตัวแปลงข้อความให้รองรับรูปแบบข้อมูลต่าง ๆ นอกเหนือจาก JSON เช่น Protobuf หรือ Avro

การปรับแต่งตัวแปลงข้อความ เป็นบทเรียน WebSockets & Real-Time Systems with Spring ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Real-Time Systems with Spring และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What are Message Converters?

In Spring WebSockets, message converters are like translators. They handle the magic of turning data from your application (like a Java object) into a format that can be sent over the network (like a JSON string or binary data), and vice-versa.

Think of them as intermediaries between your Java code and the raw WebSocket messages.

JSON: Spring's Default

By default, Spring Boot WebSockets are set up to use JSON (JavaScript Object Notation) for message conversion. This is handled by the MappingJackson2MessageConverter.

  • JSON is human-readable and widely supported.
  • It's great for most common use cases.
  • Spring automatically converts your Java objects to JSON and back.

Beyond JSON: Why Customize?

While JSON is versatile, there are times you might need other formats:

  • Performance: Binary formats (like Protobuf or Avro) are often smaller and faster to serialize/deserialize, especially for high-throughput systems.
  • Interoperability: You might need to integrate with existing systems that communicate using a specific non-JSON format.
  • Specific Needs: Custom encryption, compression, or specialized data structures.

The MessageConverter Interface

Spring uses the MessageConverter interface (from org.springframework.messaging.converter) to define how messages are handled. When you create a custom converter, you'll implement this interface.

Key methods you'd typically implement:

  • supports(Class payloadClass): Can this converter handle this type of payload?
  • fromMessage(Message message, Class targetClass): Convert an incoming message into a Java object.
  • toMessage(Object payload, MessageHeaders headers): Convert a Java object into an outgoing message.

Building a Custom Converter Logic

Let's see a simple example of the *logic* a custom converter might use. Here, we'll demonstrate converting a string to bytes (lowercase) and bytes back to a string (uppercase).

This runnable code shows the core transformation concept, mimicking what a converter does.

public class CustomConverterLogic {

    // Simulates the 'toMessage' part: Object -> Bytes
    public static byte[] stringToBytes(String text) {
        System.out.println("Converting string to bytes (lower)...");
        return text.toLowerCase().getBytes();
    }

    // Simulates the 'fromMessage' part: Bytes -> Object
    public static String bytesToString(byte[] bytes) {
        System.out.println("Converting bytes to string (upper)...");
        return new String(bytes).toUpperCase();
    }

    public static void main(String[] args) {
        String originalMessage = "Hello CoddyKit!";
        System.out.println("Original: " + originalMessage);

        // Step 1: Convert to bytes for sending
        byte[] payloadBytes = stringToBytes(originalMessage);
        System.out.println("Payload Bytes: " + new String(payloadBytes));

        // Step 2: Convert bytes back to string for receiving
        String receivedMessage = bytesToString(payloadBytes);
        System.out.println("Received: " + receivedMessage);
    }
}

Integrating with Spring Config

To tell Spring about your custom message converter, you need to register it. This is typically done by implementing WebSocketMessageBrokerConfigurer and overriding the configureMessageConverters method.

You add your custom converter to the list of converters. Spring will then try them in order.

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import java.util.List;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").withSockJS();
    }

    @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        // Add your custom converter here
        // It's often good to add custom ones before default ones if they handle the same type
        messageConverters.add(new CustomStringReverseConverter()); // Your custom converter
        messageConverters.add(new StringMessageConverter()); // Example of adding a default
        // Return true to disable default converters, false to keep them
        return false; // Keep default converters as well
    }

    // Your custom converter class would implement MessageConverter
    // For brevity, the full implementation is omitted here.
    // It would contain logic similar to the previous scene's example.
    static class CustomStringReverseConverter implements MessageConverter {
        // ... implementation of supports, fromMessage, toMessage
        @Override
        public boolean supports(Class<?> payloadClass) {
            return String.class.equals(payloadClass);
        }
        @Override
        public Object fromMessage(org.springframework.messaging.Message<?> message, Class<?> targetClass) {
            // Example: Reverse incoming string
            String payload = new String((byte[]) message.getPayload());
            return new StringBuilder(payload).reverse().toString();
        }
        @Override
        public org.springframework.messaging.Message<?> toMessage(Object payload, org.springframework.messaging.MessageHeaders headers) {
            // Example: Convert outgoing string to bytes
            return new org.springframework.messaging.support.GenericMessage<>(((String) payload).getBytes());
        }
    }
}

Order of Converters Matters

When you register multiple message converters, Spring tries them in the order they appear in the list until one reports that it supports the message's payload type.

  • If you add a custom converter that handles a type already managed by a default converter (e.g., String), place your custom converter before the default one in the list.
  • This ensures your custom logic is applied first.

Binary Formats: Protobuf & Avro

For highly optimized binary communication, formats like Protocol Buffers (Protobuf) by Google or Apache Avro are excellent choices.

  • They define data structures in a language-agnostic way.
  • Generated code handles efficient serialization and deserialization.
  • While Spring doesn't provide direct MessageConverter implementations for these by default, you can integrate existing libraries. For example, Spring Cloud OpenFeign provides a ProtobufHttpMessageConverter that can be adapted.

Client-Side Considerations

Remember, if your server uses a custom message format, your client (e.g., a JavaScript browser client or another microservice) must also know how to encode and decode that same format.

  • For Protobuf/Avro, this means using their respective client libraries.
  • For a simple custom text format, your client would need to implement the same transformation logic.

Consistency between client and server is key!

Check Your Understanding

You've learned about customizing message converters. Let's test your knowledge!

Recap: Custom Converters

Great job! In this lesson, you've learned about:

  • The role of message converters in Spring WebSockets.
  • Spring's default use of JSON and MappingJackson2MessageConverter.
  • Why and when to customize converters for performance or interoperability.
  • The MessageConverter interface and how to register your own custom converters using WebSocketMessageBrokerConfigurer.
  • Considerations for binary formats like Protobuf/Avro and the importance of client-server consistency.

Custom converters give you powerful control over your WebSocket message formats!

คำถามที่พบบ่อย

บทเรียน “การปรับแต่งตัวแปลงข้อความ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การปรับแต่งตัวแปลงข้อความ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Real-Time Systems with Spring ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Real-Time Systems with Spring มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การปรับแต่งตัวแปลงข้อความ”

ปรับแต่งตัวแปลงข้อความให้รองรับรูปแบบข้อมูลต่าง ๆ นอกเหนือจาก JSON เช่น Protobuf หรือ Avro คุณปฏิบัติ WebSockets & Real-Time Systems with Spring ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Real-Time Systems with Spring หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Real-Time Systems with Spring บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การปรับแต่งตัวแปลงข้อความ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Real-Time Systems with Spring นี้ได้ไหม

ได้ บทเรียน WebSockets & Real-Time Systems with Spring ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ตัวดักจับ WebSocket
  2. การปรับแต่งตัวแปลงข้อความ
  3. การจัดการเซสชันผู้ใช้
  4. การส่งข้อความเฉพาะเจาะจงถึงผู้ใช้
← กลับไปที่ WebSockets & Real-Time Systems with Spring