为什么 Spring 配置服务器和客户端示例一点都不清楚。?

Why Spring Config server and client example not clear at all.?

我浏览了很多链接和示例,但没有一个有效。 https://howtodoinjava.com/spring-cloud/spring-cloud-config-server-git/ https://www.baeldung.com/spring-cloud-configuration https://cloud.spring.io/spring-cloud-config/reference/html/#_spring_cloud_config_server

此处未与相关版本或任何其他依赖项共享完整信息。

所有示例中缺少的最重要的信息是依赖项的版本。

Spring 配置服务器

pom.xml 文件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.1</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>2020.0.4</spring-cloud.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>

application.properties 文件有内容

server.port=8888
spring.cloud.config.server.git.uri=file:///${user.home}/config-repo
spring.cloud.config.server.git.cloneOnStart=true

#Disable security of the Management endpoint
management.security.enabled=false

spring.security.user.name=root
spring.security.user.password=root

user.home = windows 登录用户路径。示例:“C:\Users\UserName”

Java class 启用配置注释

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

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

创建本地存储库

Create a folder "config-repo" at user folder and move to it.
git init
echo 'user.role=Developer' > config-client-development.properties
echo 'user.role=User'      > config-client-production.properties
git add .  
git commit -m 'Initial config-client properties'

Spring 配置客户端

pom.xml 文件

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.1</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>2020.0.4</spring-cloud.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bootstrap</artifactId>
    </dependency>

创建 bootstrap.properties 文件而不是 application.properties,因为我们必须在应用程序启动之前加载信息。

server.port=8800
spring.application.name=config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.username=root
spring.cloud.config.password=root
management.security.enabled=false
spring.cloud.config.fail-fast=true

Java class加载少量样本信息。

@SpringBootApplication
public class ConfigClientApplication {

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

@RefreshScope
@RestController
class MessageRestController {

    @Value("${user.role: Local value}")
    private String role;

    @Value("${msg:Config Server is not working. Please check...}")
    private String msg;

    @GetMapping("/msg")
    public String getMsg() {
        return this.msg;
    }

    @GetMapping(value = "/whoami/{username}", produces = MediaType.TEXT_PLAIN_VALUE)
    public String whoami(@PathVariable("username") String username) {
        return String.format("Hello! You're %s and you'll become a(n) %s...\n", username, role);
    }
}

现在如何运行完成申请

1.配置服务器:

Build the project 'mvn install'.
Run the application.
Test the endpoint : http://localhost:8888/config-client/development
You will see the JSON information, which will have your required data in source object.

2。配置客户端

Build the project 'mvn install'.
Run the application. You will see the starting logs as :
 /\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.1)

INFO 7796 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config 
from server at : http://localhost:8888
INFO 7796 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Located 
environment: name=config-client, profiles=[development], label=null, 
version=0000000000000000000000000, state=null
INFO 7796 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property 
source: [BootstrapPropertySource {name='bootstrapProperties-configClient'}, 
BootstrapPropertySource 

Test the endpoint : http://localhost:8800/whoami/tester
Output will be : Hello! You're tester and you'll become a(n) Developer...

我将通过我拥有的示例应用程序的代码演练向您介绍 Spring Cloud Config Server。在这里,我使用 Spring Cloud Config Server 作为我的服务器应用程序配置的中央存储库。配置服务器中定义的属性在本地不可用,它存储在单独的 GIT 存储库中。为清楚起见,请注意,我不会在此处添加整个代码块,我只会列出 spring 云配置所需的代码。

GIT 存储库中的配置文件

这是我存储库根目录中的 application.yml

# Configuration file of the application configuration server (This file holds common properties for all the microservices)

# Necessary to inform the eureka server registry, which the client is going to be registered with...  
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9090/eureka/
  
# Actuator configuration  
management:
  endpoints:
    web:
      exposure:
        include: '*'
        
# H2 database configuration 
spring:
  h2:
    console:
      enabled: true
  jpa:
    hibernate:
      ddl-auto: update
  datasource:
    platform: org.hibernate.dialect.H2Dialect
    #url: jdbc:h2:mem:bookdb
    driverClassName: org.h2.Driver 

配置服务器的POM文件(部分)

添加了 spring 云配置服务器依赖项。此操作不需要其他依赖项,但应用程序功能需要这些依赖项。因此只关注云配置服务器依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <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>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
配置服务器的

Bootstrap class

添加注释 @EnableConfigServer 表示 spring。

/**
 * Boostrap class of the library system configuration server.
 * Server responsible for handling all the configurations of each service in the application.
 * Eureka Discovery is included in the build.
 * Therefore @EnableEurekaClient is redundant.
 */
@SpringBootApplication
@EnableConfigServer
public class LibraryServerConfigurationApplication {

    /**
     * Main method of the LibraryServerConfigurationApplication.
     * @param theArguments String[]
     */
    public static void main(String[] theArguments) {
        SpringApplication.run(LibraryServerConfigurationApplication.class, theArguments);
    }

}

属性 (application.yml) 配置服务器的文件

只关注与cloud -> config -> server -> git -> uri相关的配置,其中提到了GIT配置库的路径。请修改 URI 并放入您的相关内容。

# Server port 
server:
  port: 9092

# Application configuration files are located in Git repository 
spring:
# Spring application name
  spplicatioin:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/<URL_OF_YOUR_REPOSITORY> # Git repository path

这就是您在配置服务器级别需要做的全部工作。现在让我们创建一个 Spring Cloud Config Client 以便能够从创建的配置服务器中获取配置。

Spring 云配置客户端 POM 文件(部分)

将以下依赖项添加到您的服务中,这些服务期待成为配置客户端并通过配置服务器使用配置。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

属性 配置客户端的文件更改

请注意,以下应用程序属性不在 YML 中,您可以随意使用 YML。下面的配置属性将 spring 配置服务器精确定位到 spring 配置客户端。

# Configuration client 
spring.cloud.config.import=optional:configserver:http://localhost:9092/
spring.config.import=optional:configserver:http://localhost:9092/
management.endpoints.web.exposure.include=*

那么现在我们完成了!这足够了,我们有一个功能齐全的 spring 配置服务器和一个 spring 配置客户端。这只是一个演示,请注意此配置可能会变得非常复杂和复杂,以适应不同的需求。您也可以在 GIT 存储库中维护多个应用程序 属性 文件。这肯定不会给你全部,但希望这有助于给你足够的开始和发现。