什么是服务发现
还记得在搭建tomcat集群得时候,总需要用一个配置来记录所有tomcat的物理路径,但是云部署成千上百个应用服务器时,不可能用配置文件去管理应用服务器。服务发现也叫注册中心,处理应用服务器的注册和注销,发现每个启动完成的应用,加入到集群中来,当有应用宕机或者关闭时,会自动移出集群中。还有一个好处就是抽象每一个应用服务器的物理路径,只需要知道服务名,既可以调用服务了。有这两个特性,快速地对环境中运行的服务实例数量进行水平伸缩。
上一编,我们写了一个Spring Cloud Config小demo,从Spring Cloud Config中获取数据库信息,然后获取数据库信息,启动加载数据。这次这个小demo中,加入Spring Cloud的服务发现,连接Spring Cloud Config不再使用物理路径,而是应用名。
Spring Cloud Eureka 服务发现实战
创建服务发现服务器应用
//cloud 服务注册中心
project(":eureka-server"){
dependencies {
compile "org.springframework.cloud:spring-cloud-starter-netflix-eureka-server"
}
}
添加配置文件
server:
port: 80
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #不向注册中心注册自己
fetch-registry: false # 不要在本地缓存注册表信息
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #注册中心物理路径
spring:
application:
name: eureka
启动类
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
只有使用@EnableEurekaServer
注解就可以让服务成为一个Eureka服务发现了。
在Spring Cloud Config 两个工程都引入服务注册的客户端
compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')
配置中心服务端配置
server:
port: 85
spring:
application:
name: config-server
profiles:
active: native
cloud:
config:
server:
native:
search-locations:
- file:///H://springconfig
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost/eureka #服务发现物理路径
客户端配置
server:
port: 86
spring:
application:
name: app
cloud:
config:
profile: dev
discovery:
service-id: config-server
enabled: true
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost/eureka #服务发现物理路径
在启动类添加 @EnableDiscoveryClient //自动注册
分别启动三个工程,在浏览器输入http://localhost/
image.png
eureka.client.registerWithEureka 属性时一个触发器,他可以告诉服务通过Eureka注册本身。
eureka.client.fetchRegistery Eureka客户端获取注册表的本地副本。此属性设置为true将在本地缓存注册表,而不是每次查找服务都调用Eureka服务。每个30s,客户端软件就会重新联系Eureka服务,查找注册表是否有改变。
eureka.serviceUrl.defaultZone 客户端注册中心的Eureka服务器列表,以","进行分隔多个实例。
一个简单的Eureka 服务发现就算完成的了。