java版spring cloud分布式微服务(四)分布式配置中心-b2b2c小程序电子商务

准备配置仓库
准备一个git仓库,可以在码云或Github上创建都可以。
假设我们读取配置中心的应用名为config-client,那么我们可以在git仓库中该项目的默认配置文件config-client.yml:

了解springcloud架构可以加求求:三五三六二四七二五九

info:
profile: default

为了演示加载不同环境的配置,我们可以在git仓库中再创建一个针对dev环境的配置文件config-client-dev.yml:

info:
profile: dev
1
2
构建配置中心
通过Spring Cloud Config来构建一个分布式配置中心非常简单,只需要三步:

创建一个基础的Spring Boot工程,命名为:config-server-git,并在pom.xml中引入下面的依赖(省略了parent和dependencyManagement部分):

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

创建Spring Boot的程序主类,并添加@EnableConfigServer注解,开启Spring Cloud Config的服务端功能。

@EnableConfigServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

在application.yml中添加配置服务的基本信息以及Git仓库的相关信息,例如:

spring
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: http://git.oschina.net/didispace/config-repo-demo/
server:
  port: 1201

到这里,使用一个通过Spring Cloud Config实现,并使用Git管理配置内容的分布式配置中心就已经完成了。我们可以将该应用先启动起来,确保没有错误产生,然后再尝试下面的内容。

如果我们的Git仓库需要权限访问,那么可以通过配置下面的两个属性来实现;
spring.cloud.config.server.git.username:访问Git仓库的用户名
spring.cloud.config.server.git.password:访问Git仓库的用户密码
1
2
3
完成了这些准备工作之后,我们就可以通过浏览器、POSTMAN或CURL等工具直接来访问到我们的配置内容了。了解springcloud架构可以加求求:三五三六二四七二五九.访问配置信息的URL与配置文件的映射关系如下:

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
上面的url会映射{application}-{profile}.properties对应的配置文件,其中{label}对应Git上不同的分支,默认为master。我们可以尝试构造不同的url来访问不同的配置内容,比如,要访问master分支,config-client应用的dev环境,就可以访问这个url:http://localhost:1201/config-client/dev/master,并获得如下返回:

{
    "name": "config-client",
    "profiles": [
        "dev"
    ],
    "label": "master",
    "version": null,
    "state": null,
    "propertySources": [
        {
            "name": "http://git.oschina.net/didispace/config-repo-demo/config-client-dev.yml",
            "source": {
                "info.profile": "dev"
            }
        },
        {
            "name": "http://git.oschina.net/didispace/config-repo-demo/config-client.yml",
            "source": {
                "info.profile": "default"
            }
        }
    ]
}

我们可以看到该Json中返回了应用名:config-client,环境名:dev,分支名:master,以及default环境和dev环境的配置内容。

扫描二维码关注公众号,回复: 9888479 查看本文章
发布了9 篇原创文章 · 获赞 31 · 访问量 419

猜你喜欢

转载自blog.csdn.net/m0_46413263/article/details/104825623