springcloud之Eureka服务注册与发现及服务端集群配置

一:Eureka简介

Eureka是一个基于REST的服务,用于定位服务,以实现云端中间层服务发现和故障转移。服务注册对于微服务架构来说非常重要,有了服务注册与发现,只需要使用服务的标识符,就可以访问到服务,而不需要像zookeeper一样修改服务调用的配置文件。

二:原理

微服务通过使用Eureka的客户端连接到Eureka Server并维持心跳连接。这样系统维护人员可以通过Eureka Server来监控系统中各个微服务是否正常运行。

Eureka包含两个组件:EurekaServerEurekaClient:

EurekaServer提供服务注册:

各个节点启动后,会在EurekaServer中进行注册,这样EurekaServer的服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观看到

EurekaClient是一个JAVA客户端,用户简化与Eureka Server的交互,客户端同时也具备一个内置的使用轮询负载算法的负载均衡器。在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这个服务节点移除(默认90秒)

三:Eureka的自我保护机制

关闭自我保护机制:enable-self-preservation:false

四:构建Eureka的服务端和客户端

1)配置Eureka Server的maven信息

<!-- eureka-server服务端 -->

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka-server</artifactId>

</dependency>

2)配置yml

3)设置服务端的启动类

@SpringBootApplication
@EnableEurekaServer//Eureka服务端启动类,接受其它微服务注册进来
public class EurekaServer7001_App {
	
	public static void main(String[] args) {
		SpringApplication.run(EurekaServer7001_App.class, args);
	}
	
}

客户端配置:

1)配置Eureka Client的maven信息

<!-- actuator监控信息 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

<!-- 将微服务provider侧注册进eureka -->

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka</artifactId>

</dependency>

2)服务提供方配置Eureka的客户端yml信息:

3)设置客户端启动类增加注解@EnableEurekaClient

五:发现/暴露服务

1)微服务提供方增加暴露服务注解在启动类上@EnableDiscoveryClient

2)增加暴露服务信息的方法供微服务消费者调用

	/**
	 * Eureka客户端对外暴露微服务提供者的方法信息
	 * @return
	 */
	@RequestMapping("/dept/discovery")
	public Object discovery(){
		List<String> list = discoveryClient.getServices();
		System.out.println("获得的所有服务集合:"+list.toString());
		List<ServiceInstance> serviceInstances = discoveryClient.getInstances("microservicecloud-dep");//每个服务的具体信息
		for (ServiceInstance element : serviceInstances) {
			System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+element.getPort()+"\t"+element.getUri());
		}
		return this.discoveryClient;
	}

3)微服务消费者调用服务提供者提供出来的方法

	@RequestMapping("/consumer/dept/discovery")
	public Object discovery(){
		return restTemplate.getForObject(REST_URL_PREFIX+"/dept/discovery", Object.class);
	}

六:Eureka服务端集群配置

在不同的Eureka Server工程的yml配置文件增加如下集群配置:

7003的Eureka Server配置:

7002的Eureka Server配置:

7001的Eureka Server配置:

总结:

Eureka服务端的集群就是A中的交互地址配置B、C的交互地址;

Eureka服务端的集群就是B中的交互地址配置A、C的交互地址;

Eureka服务端的集群就是C中的交互地址配置A、B的交互地址;

猜你喜欢

转载自blog.csdn.net/qq_15076569/article/details/82555925