Config学习笔记(二):使用Git存储

it2022-05-05  123

由于项目限制,以前写过一个本地配置,现在补充下Git配置。

这里采用http形式的git服务演示。

Eureka

参考

git

创建仓库

首先在git服务端创建名为cloud-config的仓库

克隆

git clone http://<ip>:<port>/**/cloud-config.git

配置文件

cd cloud-config &&\ touch application.yml &&\ echo "config.demo: Hello World!" > application.yml

推送

git add --all &&\ git commit -a -m "add property 'config.demo'" &&\ git push

服务端

初始化项目config-server

project=config-server &&\ mkdir $project &&\ cd $project &&\ gradle init --type=java-application

核心依赖

build.gradle

plugins { id "org.springframework.boot" version "2.0.4.RELEASE" id "io.spring.dependency-management" version "1.0.8.RELEASE" } dependencyManagement { imports { mavenBom "org.springframework.boot:spring-boot-starter-parent:2.0.4.RELEASE" mavenBom 'org.springframework.cloud:spring-cloud-dependencies:Finchley.SR1' } } dependencies { compile "org.springframework.cloud:spring-cloud-starter-netflix-eureka-client" compile "org.springframework.cloud:spring-cloud-config-server" }

核心配置

bootstrap.yml

server: servlet: context-path: / port: 19108 spring: application: name: config-server profiles: active: git cloud: config: server: git: uri: http://<ip>:<port>/**/cloud-config.git force-pull: true username: XXX password: XXX // 对应git分支,默认即为master default-label: master search-paths: / override-none: true eureka: instance: prefer-ip-address: true client: serviceUrl: defaultZone: http://<ip>:<port>/eureka/

启动类

重置启动类com.yan.App1,注意,注册为config服务须要在启动类上添加注解@EnableConfigServer

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

客户端

初始化项目config-client

project=config-client &&\ mkdir $project &&\ cd $project &&\ gradle init --type=java-application

核心依赖

build.gradle

compile "org.springframework.cloud:spring-cloud-starter-config"

配置

bootstrap.yml

eureka: instance: prefer-ip-address: true client: serviceUrl: defaultZone: http://<ip>:<port>/eureka/ spring: application: name: config-client cloud: config: discovery: serviceId: config-server enabled: true profile: default enabled: true

启动类

com.yan.App

@SpringBootApplication public class App { public static void main(String[] args) { ConfigurableApplicationContext run = new SpringApplicationBuilder(App.class).run(args); String demo = run.getEnvironment().getProperty("config.demo"); System.out.println("config.demo ==========> " + demo); } }

请求流程

config-client在eureka找到应用名为config-server的服务,对应的配置属性名spring.cloud.config.discovery.serviceId根据config-server中的配置spring.cloud.config.server.git.search-paths拉取所有与config-client相关的配置文件

默认的App类在根目录src/main/java下 ↩︎


最新回复(0)