Eureka:采用CS的设计架构,Eureka Server 作为服务注册功能的服务器,他是服务注册中心。而系统中的其他微服务,使用Eurkeka的客户端连接到Eureka Server,并维持心跳链接。这样系统维护人员可通过Eureka Server来监控系统中各个微服务是否正常运行。
什么是服务治理:管理服务与服务之间的依赖关系,实现服务调用,负载均衡,服务发现与注册。
什么是服务注册与发现:在服务注册与发现中,有一个注册中心(Eureka Server)。当服务启动的时候,会把当前自己服务的信息,比如服务通讯地址等以别名方式注册到注册中心上 。另一方以该别名的方式去注册中心上获取当实际的服务通讯地址,然后再实现RPC远程调用。
Eureka自我保护机制:当某个微服务不可用了,Eureka不会立刻清理,依旧对该微服务信息进行保存。默认情况下,如果Eureka Server在90秒内没有接收到某个微服务实例的心跳,Eureka Server就会注销该实例
SpringCloud 配置Eureka
pom 引入Eureka
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <version>2.2.2.RELEASE</version> </dependency>
application.yml 配置
server: port: 7001 eureka: instance: hostname: localhost #eureka服务端实例名称 client: register-with-eureka: false # 不向注册中心注册自己 #表示自己就是注册中心,职责是维护实例服务,而不需要检索服务 fetch-registry: false service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址,集群配置,多个url使用逗号隔开
在主启动类上加入 @EnableEurekaServer
@SpringBootApplication @EnableEurekaServer public class EurekaMain { public static void main(String[] args) { SpringApplication.run(EurekaMain.class, args); } }
启动项目 输入 localhost:7001/ 进行访问
zookeeper的使用步骤同Eureka类似
1.首先去zookeeper官网下载安装包,解压后进入bin目录使用./zkServer.sh start 启动zookeeper服务。
2.在微服务模块中引入zookeeper依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> <exclusions> <exclusion> <!-- 排除自带的zookeeper jar,jar版本与zookeeper 服务版本不同启动时会报jar冲突错误--> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </exclusion> </exclusions> </dependency> <dependency> <!-- 使用对应zookeeper版本的jar包--> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.6.1</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> </exclusions> </dependency>
zookeeper自带了slf4j jar,可能会与Spring boot web 自带的slf4j产生冲突,所以我把这个jar去除了。
3.配置 application.yml
server: port: 8080 #服务端口 spring: application: name: cloud-provider-payment #微服务名称 cloud: zookeeper: connect-string: 192.168.1.8:2181 #zookeeper 所在机器IP+端口
4.在主启动类上加入 @EnableDiscoveryClient 将模块发布到注册中心
5.进入zookeeper bin目录 使用./zkCli start 进入zookeeper 客户端,使用 ls /services 查看注册进来的模块。