1. Eureka简介
Eureka一词出自古希腊的词汇,词性为感叹词,意思是“我找到了!我发现了!”。据传,阿基米德在洗澡时发现了浮力原理,高兴得来不及穿上裤子,跑到街上大喊:“Eureka(我找到了)!"
在现在的微服务的架构中都会有一个注册中心,原因是微服务数量众多,要在微服务间进行远程调用需要知道服务端的ip和端口,注册中心可以管理这些服务地址和端口;另外,微服务会实时向注册中心上报自己的状态,由注册中心统一管理这些服务的状态。
Spring Cloud Eureka是一种实现了服务治理的技术,实现了服务治理的功能。Eureka提供服务端与客户端,服务端即是Eureka注册中心本身,而客户端用以完成微服务向Eureka注册中心的注册与发现。
2. 搭建简单的Eureka服务
2.1 创建spring boot项目
按一般springboot项目的创建方式创建一个springboot的项目项目即可。
2.2 涉及依赖
使用eureka作为注册中心需要spring cloud的依赖与eureka的依赖。在实际的项目中,spring cloud的依赖会放在euraka工程的父工程(parent)中。
<!-- spring cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Edgware.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- spring cloud eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2.3 启动类
Eureka的工程不需要写代码,但是要修改spring boot的启动类与配置yml文件,如下代码所示。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer // 标示该工程为eurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
2.4 修改application.yml配置文件
server:
port: 8761 # 端口
spring:
application:
name: cloud-demo-eureka # 服务名
eureka:
server:
enable-self-preservation: false # 是否开启自我保护模式
eviction-interval-timer-in-ms: 60000 # 服务注册清理间隔时间(单位:毫秒),表示每隔一分钟清理没有上报状态的服务
client:
register-with-eureka: false # 服务注册,是否将自己这一个服务注册到Eureka
fetch-registry: false # 是否从Eureka获取注册信息
service-url: # Eureka客户端与服务端交互的地址(可以在服务启动后,通过浏览器进入查看服务注册信息)
defaultZone: http://127.0.0.1:8761/eureka/
2.5 启动服务
运行spring boot的启动类,启动成功后,可以通过访问在application.yml中所配置defaultZone的值,查看注册中心运行的详细信息。
http://127.0.0.1:8761/euraka/
3. 将客户服务注册到Eureka
3.1 引入依赖
将需要注册到Eureka的服务注册到Eureka需要导入eureka client的依赖。
<!-- eureka客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
3.2 加入eureka客户端配置
在需要注册到eureka服务的yml配置文件中进行eureka客户端的配置,以下为参考配置:
eureka:
client:
registerWithEureka: true # 服务注册开关
fetchRegistry: true # 服务发现开关
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
instance:
preferIpAddress: true # 将本服务地址注册到eureka
instance-id: ${spring.cloud.client.name}:${server.port} # 实例id
3.3 启动类加上注解
在需要注册到eureka的服务启动类上加上注解,用以表示这是一个注册到eureka的服务,并可以在eureka上发现其他服务。
@EnableDiscoveryClient
@EnableEurekaClient
3.4 启动服务
在做完配置后,先启动eureka服务端的服务,接着启动客户端的服务,完成项目的启动,并可以在浏览器中查看当前注册中心的实例详情,此默认地址为:
http://127.0.0.1:8761/euraka/