Cấu Hình Trung Tâm Đăng Ký Dịch Vụ Với Eureka Trong Spring Cloud

Tổng Quan Về Eureka

Eureka thuộc bộ khung Spring Cloud, chuyên quản lý quy trình đăng ký và tìm kiếm dịch vụ. Đây là giải pháp do Netflix xây dựng, vận hành dựa trên giao thức REST, tương đồng về chức năng với các hệ thống như Zookeeper, Consul hay Nacos.

Trong kiến trúc của Eureka, hệ thống được chia làm hai thành phần chính:

  • Eureka Server: Đóng vai trò là trung tâm lưu trữ thông tin về các dịch vụ đang hoạt động.
  • Eureka Client: Có thể thực hiện cả hai nhiệm vụ là cung cấp dịch vụ (Producer) hoặc tiêu thụ dịch vụ (Consumer).

Hướng Dẫn Thiết Lập Môi Trường

Vì Spring Cloud xây dựng dựa trên nền tảng Spring Boot, bước khởi đầu tiên cần tạo một ứng dụng Spring Boot mới và tích hợp thư viện Eureka vào đó.

1. Tạo Dự Án Mẹ (Parent Project)

Dùng công cụ Maven để tạo cấu trúc đa mô-đun. Chọn đường dẫn `File > New > Project > Maven`. Khi điền thông tin GAV, sử dụng tên gói mẫu sau để minh họa:

  • groupId: vn.microservice.demo
  • artifactId: cloud-service-platform

File pom.xml tại thư mục gốc cần chứa quản lý phiên bản các thư viện con thông qua <dependencyManagement>. Các module con sẽ thừa hưởng danh sách này.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>vn.microservice.demo</groupId>
    <artifactId>cloud-service-platform</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>center-register</module>
        <module>client-service-a</module>
        <module>client-service-b</module>
    </modules>

    <properties>
        <java.version>1.8</java.version>
        <spring.boot.version>2.3.9.RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR1</spring.cloud.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Sau khi tạo xong, xóa bỏ toàn bộ thư mục src của dự án mẹ, chỉ giữ lại file cấu hình Maven.

2. Thiết Lập Trung Tâm Đăng Ký (Eureka Server)

Tạo module mới với tên center-register nằm trong thư mục cha đã định nghĩa ở trên.

File pom.xml của module server cần thêm thư viện spring-cloud-starter-netflix-eureka-server:

<project parent="cloud-service-platform">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>center-register</artifactId>

    <dependencies>
        <!-- Thư viện Web cơ bản -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- Library hỗ trợ Eureka Server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

File cấu hình application.yml cần thiết lập cổng 8761 cho server. Lưu ý thiết lập register-with-eureka: false vì đây không phải là client tự đăng ký, và fetch-registry: false vì server không cần lấy registry từ nơi khác.

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

Tạo lớp khởi động với tên CenterRegisterApplication.java và đánh dấu bởi @EnableEurekaServer:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class CenterRegisterApplication {
    public static void main(String[] args) {
        SpringApplication.run(CenterRegisterApplication.class, args);
    }
}

Khi chạy ứng dụng này và truy cập địa chỉ http://localhost:8761/, bạn sẽ thấy trang quản trị nhưng báo cáo chưa có bất kỳ dịch vụ nào (No instances available) cho đến khi các client được kích hoạt.

3. Triển Khai Các Dịch Vụ Khách Hàng (Clients)

Tiến hành tạo hai module client-service-aclient-service-b. Cả hai đều cần thêm dependency spring-cloud-starter-netflix-eureka-client.

Cấu hình application.yml tương tự nhau, chỉ khác biệt ở cổng dịch vụ (server.port) và tên ứng dụng.

# Cấu hình cho client-service-a (Cổng 8080)
server:
  port: 8080

spring:
  application:
    name: auth-service

client:
  service-url:
    defaultZone: http://localhost:8761/eureka/

Tạo lớp khởi động cho service A, sử dụng annotation @EnableDiscoveryClient hoặc @EnableEurekaClient để cho phép tự động đăng ký lên server.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class ServiceAApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceAApplication.class, args);
    }
}

Lớp khởi động cho service B cũng giống vậy nhưng đổi tên class thành ServiceBApplication và thay đổi cổng port về 8081 trong cấu hình.

4. Controller Kiểm Tra Kết Nối

Để xác nhận dịch vụ đã ghi nhận đúng, mỗi client cần có một endpoint kiểm tra trạng thái cổng kết nối.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StatusController {

    @Value("${server.port}")
    private String currentPort;

    @GetMapping("/status")
    public String checkStatus() {
        return "Dịch vụ đang hoạt động trên cổng " + currentPort;
    }
}

Kết quả cuối cùng khi truy cập các cổng riêng biệt (/status) sẽ trả về dòng chữ hiển thị số cổng tương ứng. Trên giao diện của Eureka Server, bạn sẽ thấy hai nút tròn đại diện cho auth-service (hoặc tên tùy chỉnh), cho thấy cả hai node con đều đã liên kết thành công với trung tâm.

Thẻ: spring-cloud eureka Microservices service-discovery netflix

Đăng vào ngày 24 tháng 5 lúc 07:01