SpringCloud-Eureka注册中心
一、Eureka的作用
- 首先先来看一下下面这幅图,并结合下面问题看看自己需要解决哪些问题。
- order-server在发送远程调用的时候,该如何得知user-server实例的ip地址和端口?
(1) user-service服务实例启动后,将自己的信息注册到eureka-server(Eureka服务端)。这个叫服务注册。
(2) eureka-server保存服务名称到服务实例地址列表的映射关系。
(3) order-service根据服务名称,拉取实例地址列表。这个叫服务发现或服务拉取。 - 有多个user-server实例地址,order-server调用时该如何选择?
(1)user-service服务实例启动后,将自己的信息注册到eureka-server(Eureka服务端)。这个叫服务注册
(2)eureka-server保存服务名称到服务实例地址列表的映射关系 - order-server如何得知某个user-server实例是否依然健康,是不是已经宕机?
(1)user-service会每隔一段时间(默认30秒)向eureka-server发起请求,报告自己状态,称为心跳
(2)当超过一定时间没有发送心跳时,eureka-server会认为微服务实例故障,将该实例从服务列表中剔除
(3)order-service拉取服务时,就能将故障实例排除了
二、搭建eureka-server
- 首先搭建注册中心服务端:euraka-server,这个必须是一个独立的微服务。
2.1、创建eureka-server服务
- 在父工程里面创建一个子模块(也就是创建一个maven)。
- 在创建好的maven里面引入springCloud为eurake提供的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 给eureka-server服务编写一个启动类,一定要在启动类上添加一个@EnableEurekaServer注解,开启euraka的注册中心功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
- 编写一个application.yaml文件:
server:
port: 10086 # 这个是自己定义的
spring:
application:
name: eureka-server # 这个名称就是服务的名称
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
- 启动微服务,然后在浏览器访问:http://127.0.0.1:10086
2.2、服务注册
- 上面已经将注册中心搭建完成,接下来我们就可以将user-server注册到eureka-server中去了。
- 首先,在user-server的pom文件中引入下面的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在user-server中,修改application.yaml文件,添加服务名称、eureka地址:
spring:
application:
name: userservice # 服务名称
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka # eureka地址
- 上面就完成服务注册。
2.3、服务发现
- 上面我们已经将user-sever注册到注册中心里面了,现在需要让order-server在注册中心里面发现user-server。
- 首先在order-server里面引入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 然后修改order-server的application.yaml文件:
spring:
application:
name: orderservice # 服务名称,自己起一个
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka # eureka地址
- 最后,我们要去eureka-server中拉取user-service服务的实例列表,并且实现负载均衡。
不过这些动作不用我们去做,只需要添加一些注解即可。
在order-service的OrderApplication中,给RestTemplate这个Bean添加一个@LoadBalanced注解:
- 在order-sever服务里面创建一个url,并使用上图注册进去的ResetTemaplate的getForObject方法发起调用:
spring会自动帮助我们从eureka-server端,根据userservice这个服务名称,获取实例列表,而后完成负载均衡。