当前微服务下注册服务和发现不外乎Eureka\Zookeeper\consul这三种,当然alibaba的nacos也是非常好用,nacos后期会专门讲一下。
Eureka:
从18年开始,基本上springCloud项目都会用,两大插件 client和service
首先都会写一个注册中心,注册中心调用service插件,依赖如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
然后写一个application.yml
server:
port: 7001
eureka:
instance:
hostname: localhost #eureka服务端的实例名称
client:
register-with-eureka: false #false表示不向注册中心注册自己。
fetch-registry: false #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务
service-url:
#集群指向其它eureka
# defaultZone: http://eureka7002.com:7002/eureka/
#单机就是7001自己
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
server:
# 关闭自我保护机制,保证不可用服务被及时踢除
enable-self-preservation: false
eviction-interval-timer-in-ms: 2000
最后写一个启动类即可
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication7001.class,args);
}
}
而向他注册的服务,称为客户端,调用client插件,
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
yml文件增加以下配置:
eureka:
client:
#表示是否将自己注册进EurekaServer默认为true。
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
#单机版
defaultZone: http://localhost:7001/eureka
# 集群版
#defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
启动类上有
@EnableEurekaClient
Zookeeper:
在Linux环境下安装Zookeeper,关闭防火墙,(linuxsystemctl stop firewalldsystemctl status firewalld 2.windows)
然后ping连接网络。
服务代码中 pom增加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<!--先排除自带的zookeeper3.5.3-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
yml文件增加以下配置:
spring:
cloud:
zookeeper:
connect-string: localhost:2181
启动类增加
@EnableDiscoveryClient
Consul:
https://www.consul.io/downloads.html
安装网址,非常详细 贴心的提供了安装动画,跟着走就行。
POM文件增加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
yml文件:
spring:
application:
name: consul-provider-payment
####consul注册中心地址
cloud:
consul:
host: localhost
port: 8500
discovery:
#hostname: 127.0.0.1
service-name: ${spring.application.name}
启动类增加
@EnableDiscoveryClient
区别在于:
eureka是CAP理论中的AP结构,Zookeeper和consul是属于CP结构。既 eureka侧重服务可用性,Zookeeper和consul侧重数据一致性。eureka侧重服务可用性是依据它的自我保护机制,就是短时间内大量服务宕机,eureka认为是网络问题,不会将其从服务列表移除,而Zookeeper和consul在心跳机制内发现服务不存在就会移除服务。