คู่มือ Java ฉบับทันสมัย (อัปเดตล่าสุดปี 2025)

 คู่มือ Java ฉบับทันสมัย (อัปเดตล่าสุดปี 2025) บทนำ Java ยังคงเป็นภาษายอดนิยมที่ได้รับความนิยมอย่างต่อเนื่องตั้งแต่ยุค 1990 จนถึงปัจจุบัน ในปี 2025 Java ได้ก้าวหน้าอย่างมากทั้งด้านภาษาหลักและเครื่องมือสนับสนุน ล่าสุด Java 24 ได้เปิดตัวออกมาแล้ว และ Java 21 เป็นเวอร์ชัน LTS (Long-Term Support) ที่แนะนำให้ใช้งานสำหรับระบบจริงในระยะยาว บทความนี้จะช่วยให้คุณเข้าใจภาพรวมของ Java เวอร์ชันล่าสุด รวมถึงฟีเจอร์เด่น โครงสร้างภาษาที่ควรรู้ และแนวทางการพัฒนา Java ยุคใหม่ ภาพรวมเวอร์ชัน Java ล่าสุด เวอร์ชัน สถานะ วันเปิดตัว Java 24 เวอร์ชันล่าสุด มีนาคม 2025 Java 21 เวอร์ชัน LTS ล่าสุด กันยายน 2023 Java 17 LTS รุ่นก่อนหน้า กันยายน 2021 Java 11 LTS เก่า กันยายน 2018 โครงสร้างพื้นฐานของภาษา Java คลาสและอ็อบเจกต์ : โครงสร้างหลักของโปรแกรม Java Primitive Types : int, double, char, boolean เป็นต้น Control Statements : if, switch, while, for, do-while Methods : การแยกโค้ดเป็นหน่วยที่นำกลับมาใช้ซ้ำได้ Array และ Collection : จัดเก็บและจัดการข้อมูลหลายรายการ Exception Handling : try-catch-finally OOP Co...

สอนสร้างเกมส์บริหารเหตุการณ์ต่างๆในร้านนวด

ตัวอย่างสุ่มเหตุการณ์ต่างๆในร้านนวด ที่เหลือต่อยอดเอาเองนะครับ ^^

ในบทความนี้ เราจะสร้างระบบบริหารร้านนวดโดยใช้ Spring Boot ซึ่งมีฟีเจอร์ต่างๆ เช่น:

  • สุ่ม Event ที่ส่งผลกระทบต่อ Entity
  • แจ้งสถานะผลกระทบผ่าน WebSocket
  • อัปเดตข้อมูลในฐานข้อมูลโดยตรง

1. WebSocket Configuration

@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("/event-websocket").setAllowedOrigins("*").withSockJS();
    }
}
    

2. Event Entity

@Entity
public class Event {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String type;
    private String description;
    private double impact;
    private String affectedEntity;
    private Long affectedId;

    // Getters and Setters
}
    

3. Event Service

@Service
public class EventService {
    private final Random random = new Random();
    private final SimpMessagingTemplate messagingTemplate;
    private final RoomRepository roomRepository;
    private final MassageTherapistRepository therapistRepository;
    private final CustomerRepository customerRepository;

    public EventService(SimpMessagingTemplate messagingTemplate,
                        RoomRepository roomRepository,
                        MassageTherapistRepository therapistRepository,
                        CustomerRepository customerRepository) {
        this.messagingTemplate = messagingTemplate;
        this.roomRepository = roomRepository;
        this.therapistRepository = therapistRepository;
        this.customerRepository = customerRepository;
    }

    @Scheduled(fixedRate = 10000) // สุ่มทุก 10 วินาที
    public void generateRandomEvent() {
        Event event = new Event();
        String affectedEntity = randomAffectedEntity();
        Long affectedId = applyImpactToEntity(affectedEntity);

        event.setType(randomEventType());
        event.setDescription(randomEventDescription(event.getType(), affectedEntity));
        event.setImpact(randomImpactValue());
        event.setAffectedEntity(affectedEntity);
        event.setAffectedId(affectedId);

        // ส่ง Event ไปยัง WebSocket
        messagingTemplate.convertAndSend("/topic/events", event);
    }

    private String randomAffectedEntity() {
        String[] entities = {"Room", "MassageTherapist", "Customer"};
        return entities[random.nextInt(entities.length)];
    }

    private String randomEventDescription(String type, String entity) {
        switch (type) {
            case "Positive": return entity + " ได้รับผลกระทบเชิงบวก!";
            case "Negative": return entity + " ได้รับผลกระทบเชิงลบ!";
            default: return "ไม่มีผลกระทบที่ชัดเจน.";
        }
    }

    private double randomImpactValue() {
        return random.nextDouble() * 100 - 50; // ค่าผลกระทบระหว่าง -50 ถึง 50
    }

    private Long applyImpactToEntity(String entity) {
        switch (entity) {
            case "Room":
                return applyImpactToRoom();
            case "MassageTherapist":
                return applyImpactToTherapist();
            case "Customer":
                return applyImpactToCustomer();
            default:
                return null;
        }
    }

    private Long applyImpactToRoom() {
        List<Room> rooms = roomRepository.findAll();
        if (rooms.isEmpty()) return null;

        Room room = rooms.get(random.nextInt(rooms.size()));
        room.setCapacity(room.getCapacity() + random.nextInt(5) - 2); // เพิ่ม/ลดความจุ
        roomRepository.save(room);
        return room.getId();
    }

    private Long applyImpactToTherapist() {
        List<MassageTherapist> therapists = therapistRepository.findAll();
        if (therapists.isEmpty()) return null;

        MassageTherapist therapist = therapists.get(random.nextInt(therapists.size()));
        therapist.setSkillLevel(Math.max(0, therapist.getSkillLevel() + random.nextInt(3) - 1)); // เพิ่ม/ลดทักษะ
        therapistRepository.save(therapist);
        return therapist.getId();
    }

    private Long applyImpactToCustomer() {
        List<Customer> customers = customerRepository.findAll();
        if (customers.isEmpty()) return null;

        Customer customer = customers.get(random.nextInt(customers.size()));
        customer.setSatisfaction(Math.max(0, customer.getSatisfaction() + random.nextDouble() * 10 - 5)); // เพิ่ม/ลดความพึงพอใจ
        customerRepository.save(customer);
        return customer.getId();
    }
}
    

4. Frontend Integration

<script src="https://cdn.jsdelivr.net/npm/sockjs-client"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs"></script>
<script>
    const socket = new SockJS('/event-websocket');
    const stompClient = Stomp.over(socket);

    stompClient.connect({}, () => {
        stompClient.subscribe('/topic/events', (message) => {
            const event = JSON.parse(message.body);
            console.log("Received event:", event);
            alert(`Event: ${event.description}, Impact: ${event.impact}`);
        });
    });
</script>
    

ถ้าต้องการปรับแต่งเพิ่มเติม สามารถดูรายละเอียดในโค้ดต้นฉบับได้ครับ!

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

คู่มือ Java ฉบับทันสมัย (อัปเดตล่าสุดปี 2025)

การใช้งาน RPC (Remote Procedure Call) ด้วย Java พร้อมตัวอย่างเกมออนไลน์ (ต่อ)