Code ví dụ Spring Cloud Config Client

Code ví dụ Spring Cloud Config Client

Trong ví dụ này chúng ta sẽ thực hiện load cấu hình để sử dụng cho project từ 1 server khác (Spring Cloud Config)

Việc load cấu hình từ 1 server khác thường áp dụng cho các project có nhiều instance trên nhiều server, mỗi lần đổi cấu hình ta chỉ cần đổi cấu hình trên server config là được chứ không cần phải sửa cho từng server một.

(Xem lại: Code ví dụ Spring Cloud Config Server)

Code ví dụ Spring Cloud Config Client

Tạo project Spring Boot: File > New > Module

Code ví dụ Spring Cloud Config Client Code ví dụ Spring Cloud Config Client Code ví dụ Spring Cloud Config Client

Cấu trúc project sau khi hoàn thành:

Code ví dụ Spring Cloud Config Client

File Application: (giống hệt các project spring boot thông thường)

package stackjava.com.scconfigclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringCloudConfigClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudConfigClientApplication.class, args);
    }

}

File bootstrap.yml:

spring:
  application:
    name: app
  profiles:
    active: dev
  cloud:
    config:
      uri: http://localhost:8888

Đây là một project spring cloud nên các thông tin cấu hình về server config, name ta sẽ đặt trong file bootstrap.yml

Trong ví dụ này mình sẽ load cấu hình từ server có địa chỉ http://localhost:8888, cấu hình được load sẽ có tên là app với profiles là dev. (Đây là server mình đã dựng trong bài trước)

(Xem lại: Sự khác nhau giữa file application với file bootstrap trong spring)

File application.yml

server:
  port: 7777

Server sẽ chạy trên port 7777

File controller:

package stackjava.com.scconfigclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class HomeController {
    @Value("${database.host}")
    private String host;
    @Value("${database.database}")
    private String database;
    @Value("${database.username}")
    private String username;
    @Value("${database.password}")
    private String password;

    @GetMapping("/config")
    public String config() {
        return "host: " + host + "<br/>username: " + username + "<br/>password: " + password + "<br/>database: " + database;
    }
}

 

Annotation @RefreshScope là 1 annotation của spring cloud. Các Bean được đánh dấu với annotation này sẽ được làm mới tại thời gian chạy (runtime). Mỗi khi gọi tới thì nó sẽ tạo 1 bean mới.

Start project:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)

2020-08-20 14:20:12.155  INFO 12476 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2020-08-20 14:20:12.984  INFO 12476 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=app, profiles=[dev], label=null, version=31254e088069d8f5c2651156237f2973613a9781, state=null
2020-08-20 14:20:12.985  INFO 12476 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-configClient'}, BootstrapPropertySource {name='bootstrapProperties-C:/Users/stackjava/Desktop/spring-cloud-config-server-repo/app-dev.properties'}, BootstrapPropertySource {name='bootstrapProperties-C:/Users/stackjava/Desktop/spring-cloud-config-server-repo/app.properties'}]
...
2020-08-20 14:20:14.616  INFO 12476 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 7777 (http) with context path ''
2020-08-20 14:20:15.227  INFO 12476 --- [           main] s.c.s.SpringCloudConfigClientApplication : Started SpringCloudConfigClientApplication in 5.492 seconds (JVM running for 6.63)
2020-08-20 14:20:19.989  INFO 12476 --- [nio-7777-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-20 14:20:19.989  INFO 12476 --- [nio-7777-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-20 14:20:19.992  INFO 12476 --- [nio-7777-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms

Mở trình duyệt web và truy cập vào địa chỉ: http://localhost:7777/config

Code ví dụ Spring Cloud Config Client

Mặc dù các biến database.host, database.name... không có trong file cấu hình là application.yml nhưng nó vẫn có giá trị là do chúng đã được load từ server config.

 

Trong bài tiếp theo chúng ta sẽ tìm hiểu việc authen khi giao tiếp giữa spring cloud config server với spring cloud config client. Refresh lại cấu hình cho client khi cấu hình trên server, repository được thay đổi.

 

Okay, Done!

Download code ví dụ trên tại đây hoặc tại: https://github.com/stackjava/spring-cloud-config-client

References: https://cloud.spring.io/spring-cloud-config/reference/html/#_spring_cloud_config_client

stackjava.com