创建Eureka注册中心服务器
关键依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</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>
yml配置文件:
server:
port: 9100 #端口号
eureka:
instance:
hostname: localhost #注册中心地址
client:
register-with-eureka: false #是否将自己注册到注册中心
fetch-registry: false #是否从注册中心检索服务
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
在启动类中使用@EnableEurekaServer注解开启注册中心服务:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
启动应用在浏览器访问http://localhost:8100:
注册服务
创建一个用户服务app-user,注册到Eureka注册中心。
关键依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
<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-client</artifactId>
</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>
yml配置文件:
server:
port: 8010
spring:
application:
name: app-user #服务别名-注册到注册中心之后的名称
eureka:
client:
register-with-eureka: true #注册到注册中心
fetch-registry: true #检索其他服务
serviceUrl:
defaultZone: http://localhost:9100/eureka/ #注册目标地址
在启动类中使用@EnableEurekaClient将用户服务注册到Eureka注册中心:
@SpringBootApplication
@EnableEurekaClient
public class UserServerApplication {
public static void main(String[] args) {
SpringApplication.run(UserServerApplication.class, args);
}
}
再次打开注册中心页面http://localhost:8100,就可以看到app-user服务已经被注册进来了