二十、springcloud(六)配置中心服务化和高可用
1、问题描述
前一篇,spring-cloud-houge-provider(称之为客户端)直接从spring-cloud-houge-config(称之为服务端)读取配置,客户端和服务端的耦合性太高,服务端改变IP地址的时候,客户端也需要修改配置,不符合springcloud服务治理的理念。我们只需要将server端当做一个服务注册到eureka中,client端去eureka中去获取配置中心server端的服务既可。spring-cloud-houge-provider当提供接口服务时为server端,当读取属性文件时为client端,切莫混淆。
2、服务端修改,spring-cloud-houge-config
a、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
b、配置文件增加了eureka注册中心的配置
spring.application.name=spring-cloud-config-server server.port=8001 #读取本地文件 spring.profiles.active=native eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
c、启动类
@EnableDiscoveryClient @EnableConfigServer //激活对配置中心的支持 @SpringBootApplication public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
3、客户端修改,spring-cloud-houge-provider
a、添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
b、application.properties
spring.application.name=spring-cloud-provider server.port=9000 management.security.enabled=false
c、bootstrap.properties
spring.cloud.config.name=config spring.cloud.config.profile=dev #spring.cloud.config.uri=http://localhost:8001/ #开启Config服务发现支持 spring.cloud.config.discovery.enabled=true #指定server端的name,也就是server端spring.application.name的值 spring.cloud.config.discovery.serviceId=spring-cloud-config-server #注册中心 eureka.client.serviceUrl.defaultZone=http://localhost:8000/eureka/
d、启动类
@SpringBootApplication @EnableDiscoveryClient //使项目有服务注册功能 public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
4、启动服务
启动注册中心:http://localhost:8000/
启动config:http://localhost:8001/config-dev.properties
启动spring-cloud-houge-provider

http://localhost:9000/dynasty/hello?name=monkey

5、高可用
为了模拟生产集群环境,我们改动server端的端口为8003,再启动一个server端来做服务的负载,提供高可用的server端支持。防止某一台down掉之后影响整个系统的使用。代码重复,请自行测试
浙公网安备 33010602011771号