Spring Cloud Eureka:服务治理
Spring Cloud Eureka是Spring Cloud Netflix服务套件中的一部分,它基于Netflix Eureka做了二次封装,主要负责完成微服务架构中的服务治理,接下来将展示入门Demo。
开发环境 | 版本 |
---|---|
IDEA | 2018.2.6 |
JDK | 1.8 |
Spring Boot | 2.1.0 |
Spring Cloud | Greenwich.M1 |
Eureka服务端
新建项目
在IDEA中通过Spring Initializr创建项目,选择Spring Boot 2.1.0版本、选择Maven依赖Eureka Server(Cloud Discovery中)。
<dependencies>
<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>
加入注解
在入口类添加@EnableEurekaServer注解。
@SpringBootApplication
@EnableEurekaServer // 开启Eureka注册服务
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
添加配置
在文件application.yml添加配置。
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: false #禁止自身注册
# server:
# enable-self-preservation: false
instance:
prefer-ip-address: true #默认显示IP
instance-id: ${spring.cloud.client.ip-address}:${server.port}
# hostname: ServerName
spring:
application:
name: eureka
运行项目
在VM options设置-DServer.port=8761,运行项目,浏览器打开http://localhost:8761即可看到Eureka页面。
Eureka客户端
新建项目
在IDEA中通过Spring Initializr创建项目,选择Spring Boot 2.1.0版本、选择Maven依赖Web和Eureka Discovery(Cloud Discovery中)。
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
加入注解
在入口类添加@EnableEurekaClient注解。
@SpringBootApplication
@EnableEurekaClient //开启Eureka发现
public class FeignProviderApplication {
public static void main(String[] args) {
SpringApplication.run(FeignProviderApplication.class, args);
}
}
添加配置
在文件application.yml添加配置。
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
# hostname: ProviderName
instance-id: ${spring.cloud.client.ip-address}:${server.port}
spring:
application:
name: provider
运行项目
在VM options设置-DServer.port=8081,运行项目,在Eureka页面可以看到如下图线框处,证明本项目启动时已自动注册成功。
附件