一、注册中心
1、新建service服务,导入jar包
spring-cloud-starter-eureka-server 已经被遗弃,现使用spring-cloud-starter-netflix-eureka-server
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
2、启动服务注解
启动服务类添加注解@EnableEurekaServer
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
3、添加配置信息
server:
port: 8761 # 一般默认为8761
spring:
application:
name: eureka
eureka:
instance:
hostname: localhost
client:
service-url:
defalultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
register-with-eureka: false # 不允许注册服务到注册中心
fetch-registry: false # 不允许请求被注册的服务
4、访问注册中心
http://localhost:8761/
注: 先启动注册中心,再启动client。
5、心跳机制
默认是30 ,注册中心每过一段时间和client服务交互一次,确认服务是正常,若服务异常则剔出服务。
二、client服务
1、新建client服务,导入jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2、启动服务注解
启动服务类添加注解@EnableEurekaClient
@EnableDiscoveryClient 和 @EnableEurekaClient 都是用于服务注册。
区别:
@EnableEurekaClient只能用于Eureka注册中心
@EnableDiscoveryClient 可用于任何注册中心
@SpringBootApplication
@EnableEurekaClient
public class UserServerApplication {
public static void main(String[] args) {
SpringApplication.run(UserServerApplication.class, args);
}
}
3、添加配置信息
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/