目前的方式,SpringCloudConfigClient只能调用固定的一个Server,一旦Server出现异常,正式调用将会中断。
回顾之前样例,不能得出解决方法,写多个Server注册到Eureka-Server上,然后配置相同Service-Name,然后利用负载均衡处理。
本章节代码使用仍旧只注册一个Client到Eureka,不过SpringCloudConfigClient获取数据不再是通过SpringCloudConfigServer,而是通过注册到了SpringCloudEurekaServer
准备
使用之前项目eureka-colony ,直接启动即可
改造服务端
修改springcloud-config-server,注册成eureka客户端。
pom文件添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
配置文件添加服务端地址
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://github.com/keith002/springcloud-eureka/
search-paths: config
username:
password:
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://admin:admin@localhost:8761/eureka/
启动类添加注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class SpringcloudConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudConfigServerApplication.class, args);
}
}
至此服务端改造完成,启动后可以查看到注册上了。
改造客户端
修改springcloud-config-server,注册成eureka客户端。
pom文件添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
配置文件添加服务端地址
bootstrap.properties
spring.application.name=config
spring.cloud.config.label=master
spring.cloud.config.profile=dev
#spring.cloud.config.uri= http://127.0.0.1:8081/
server.port=8082
eureka.client.serviceUrl.defaultZone=http://admin:admin@localhost:8761/eureka/
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.serviceId=config-server
注:同时加了config和eureka注解。去掉config注解,都很正常。那我们来看看,其实我们加了@EnableConfigServer这个注解后,对于请求http://localhost:8080/**/**
的请求默认被config拦截了,http://localhost:8080/eureka/css/wro.css 和http://localhost:8080/eureka/js/wro.js 这两个请求。 发现了问题之后,后面我在application.properties配置文件里面新增了spring.cloud.config.server.prefix=/config
,给config增加了/config访问前缀,这样,/eureka 的请求就会被放行,这样自然就成功了啦! 如果是其他配置导致的,处理方式相类似。