我所使用的工具是idea,以下介绍的是在idea中来搭建服务注册中心。
步骤如下:
一、新建项目
二、配置注册中心
1、首先我们来看一下pom.xml中的依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <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 Server依赖,自己手动添加式,特别需要注意一下Spring Boot和Spring Cloud版本对应关系,否则依赖添加不成功。
出现的问题:使用@EnableEurekaServer注解识别不了。
2、在Spring Boot的启动类上通过@EnableEurekaServer注解启动一个服务注册中心提供给其他应用进行对话:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
3、在application.properties文件中配置这个注册中心:
#设置服务注册中心的端口 server.port=1111 #配置当前实例的主机名称 eureka.instance.hostname=localhost #设置为false,表示不向注册中心注册自己 eureka.client.register-with-eureka=false #设置为false,是因为注册中心的职责是维护服务实例,并不需要去检索服务 eureka.client.fetch-registry=false #设置注册中心的地址 eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
eureka.client.register-with-eureka:由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己。
eureka.client.fetch-registry:由于注册中心的职责就是维护服务实例,它并不需要去检索服务,所以也设置为false。
3、启动应用并访问http://localhost:1111/,可以看到如下图所示的Eureka信息面板,其中Instance currently registered with
Eureka栏是空的,说明该注册中心还没有注册任何服务。