spring cloud(五、配置中心)

在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。

一、设置一个配置中心(eureka-config)

类似注册中心,引入spring-cloud-config-server,spring-cloud-starter-netflix-eureka-server依赖

注册中心和配置中心可以为同一个

启动类:

@SpringBootApplication
@EnableEurekaServer
public class EurekaConfigApplication {

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

配置文件:

server:
  port: 8889

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

二、配置连接(config-server)

连接配置文件管理的地方

引入spring-cloud-starter-netflix-eureka-server和spring-cloud-config-server依赖

启动类:

@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigServerApplication {

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

配置文件:

spring.application.name=config-server
server.port=8888

spring.cloud.config.server.git.uri=https://github.com/forezp/SpringcloudConfig/
spring.cloud.config.server.git.searchPaths=respo
spring.cloud.config.label=master
spring.cloud.config.server.git.username= your username
spring.cloud.config.server.git.password= your password
eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/

三、使用配置文件(config-client)

引入spring-cloud-starter-config和spring-cloud-starter-netflix-eureka-server依赖

启动类:

@SpringBootApplication
@EnableEurekaClient
@RestController
@RefreshScope
public class ConfigClientApplication {

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

	@Value("${foo}")
	String foo;

	@RequestMapping(value = "/hi")
	public String hi(){
		return foo;
	}
}

配置文件(配置文件名必须是bootstrap.properties):

spring.application.name=config-client
spring.cloud.config.label=master
spring.cloud.config.profile=dev
#spring.cloud.config.uri= http://localhost:8888/

eureka.client.serviceUrl.defaultZone=http://localhost:8889/eureka/
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.serviceId=config-server
server.port=8881

结果:

源码:https://github.com/lrn-white/springcloud

猜你喜欢

转载自blog.csdn.net/qq_33283652/article/details/82771363