spring cloud+dotnet core搭建微服务架构:配置中心

前言

我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心。一般配置都是存储到配置文件里面,不管多小的配置变动,都需要对应用程序进行重启,对于分布式系统来说,这是非常不可取的。所以配置中心就在这种场景孕育出来,能够适配不同的环境,正在运行的程序不用重启直接生效。

介绍

现在开始介绍我们今天的主角spring cloud config,我觉得它最大的优点就是可以和git做集成,使用起来非常方便。spring cloud config包含服务端和客户端,服务端提供配置的读取和配置仓库,客户端来获取配置。

也可以使用svn或者文件来存储配置文件,我们这里只讲Git的方式

业务场景

我们模拟一个业务场景,有一个远程配置文件我们通过应用程序获取它。

代码实现

我们需要创建2个应用程序:配置服务服务端(Java),配置服务客户端(.Net Core)和一个Github仓库。
使用IntelliJ IDEA创建一个spring boot项目,创建配置中心服务端,端口设置为5100

pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
ConfigServerApplication.java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
application.properties
server.port=5100
spring.application.name=config-server
#git仓库地址
spring.cloud.config.server.git.uri=https://github.com/longxianghui/configs.git
#git用户名和密码
#spring.cloud.config.server.git.username=xxx
#spring.cloud.config.server.git.password=xxx
#git目录下的文件夹,多个用逗号分割
#spring.cloud.config.server.git.search-paths=xxx,xxx,xxx

使用Github创建一个仓库,并提交3个文件,文件内容如下(注意yml格式)

demo-dev.yml
name: mickey
age: 3
env: test
demo-test.yml
name: fiona
age: 28
env: test
demo-prod.yml
name: leo
age: 30
env: prod

配置文件命名规则{application}-{profile}.yml
支持yml和properties格式

运行配置中心服务端
在浏览器输入http://localhost:5001/demo/dev
image
再访问http://localhost:5001/demo/test
image
再访问http://localhost:5001/demo/prod
image
通过上面3个URL我们发现配置中心通过REST的方式将配置信息返回。
配置服务REST规则如下:

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

下面我们再看看.NET程序如何读取配置信息呢?
创建一个 .net core web api程序,端口5101

nuget引用
<PackageReference Include="Steeltoe.Extensions.Configuration.ConfigServer" Version="1.1.0" />
appsettings.json
{
  "spring": {
    "application": {
      "name": "demo"//与配置文件的名称对应
    },
    "cloud": {
      "config": {
        "uri": "http://localhost:5100",
        "env": "dev" //与环境名称对应
      }
    }
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}【本文由“程序员单身狗”发布,2017年10月13日】
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值