创建Eureka server工程
使用spring boot项目快速构建工具(spring initializr)创建spring boot工程,在过程中选择Eureka server选项,项目构建完成会自动在pom中引入Eureka server相关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
主启动类上添加@EnableEurekaServer
注解
编写Eureka服务端yml配置文件
server:
port: 8000
spring:
application:
name: koala-eureka
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #服务端必配,禁止自生注册
fetch-registry: false #服务端必配,表示自己就是注册中心,不需要去检索服务
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
注意:其中的service-url.defaultZone中最后必须为/eureka,这个时Eureka服务端固定的服务地址,不写或写为其它内容则在其他服务注册时找不到Eureka服务端
Eureka客户端服务的创建
使用spring initializr创建spring boot工程,勾选Eureka clinet选项,默认情况下pom中会有如下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
主启动类上添加@EnableEurekaClient
注解
编写Eureka客户端yml
url:
eureka: localhost:8000/eureka/ #Eureka服务端地址
server:
port: 8001
servlet:
context-path: /user-center
spring:
application:
name: user-center
datasource:
url: jdbc:mysql://localhost:3306
username: root
password: root
eureka:
client:
service-url:
defaultZone: http://${url.eureka} #此处必须与Eureaka服务端地址相同
instance:
instance-id: ${spring.application.name}:${server.port} #实例名
prefer-ip-address: true #配置是否显示ip地址,默认为false
info: #点击实例后展示的info界面
app.name: @project.artifactId@
app.version: @project.version@
@project.artifactId@,使用这种写法,可以引用pom的变量,从而动态的显示配置在pom中的应用名、版本号等信息
至此便完成了Eureka服务端与客户端的创建,完成了服务的注册与发现