简介
Eureka是Netffix下面的注册中心组件,在springCould中,官方提供的注册中心组件为consul,Netffix则提供了Eureka,alibaba提供了Nacos。Eureka基于REST的服务,以实现云端中间层服务发现和故障转移。
Eureka Server 简单使用
- 首先新建一个空项目,并在空项目下创建子模块eureka-learn,同时,修改其pom文件,将parent设置为springboot版本以及设置springCloud的相应版本;
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath />
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-cloud.version>Hoxton.SR12</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 在eureka-learn子模块中创建模块eureka-server
在模块eureka-server的pom文件中加入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 配置文件中配置启动端口为8761,同时我们应该设置应用的名称;
server:
port: 8761 # 端口指定为8761,不要修改
spring:
application:
name: eureka-server
- 最后,我们在启动类上加上注解==@EnableEurekaServer==,启动应用,在浏览器通过http://localhost:8761即可访问。
现在我们就简单的完成了eureka server的使用。
Eureka Client 简单使用
- 与上面eureka server的过程相似,我们首先创建一个子模块eureka-client
- 导入eureka client依赖;
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
注意: 一定不能忘记web依赖,否则项目启动后会马上停止。
- 增加配置文件application.yml并添加配置:
server:
port: 8081 # 端口没有要求
spring:
application:
name: eureka-client
eureka:
client:
service-url: # 指定注册的地址
defaultZone: http://localhost:8761/eureka
- 在启动类加注解==@EnableEurekaClient==,并启动服务;
- 刷新浏览器eureka server界面,我们的实例以及注册到了eureka注册中心并且上线实例数目为1;
以上,我们便完成了eureka client的简单使用。