Spring Cloud – 服务发现(Eureka)
该项目是Spring Cloud的子项目之一,主要内容是对Netflix公司一系列开源产品的包装,它为 Spring Boot 应用提供了自配置的Netflix OSS整合。通过一些简单的注解,开发者就可以快速的在应用中配置一下常用模块并构建庞大的分布式系统。它主要提供的模块包括:服务发现( Eureka ),断路器( Hystrix ),智能路有( Zuul ),客户端负载均衡( Ribbon )等。
1.创建EurekaServer
创建一个SpringBoot项目,在pom.xml文件中加入 Eureka-server 依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
启动服务注册中心。这一步非常的简单,只需要在入口类上添加@EnableEurekaServer注解就能开启此功能,比如下面的例子:
@SpringBootApplication @EnableEurekaServer public class DiscoveryServiceApplication { public static void main(String[] args) { SpringApplication.run(DiscoveryServiceApplication.class, args); } }
特别注意:在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为,只需要在application.yml中问增加如下配置:
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false #表明自己是一个eureka server
fetchRegistry: false #表明自己是一个eureka server
serviceUrl:
defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/
- 启动工程,打开浏览器访问Eureka界面。网址:http://localhost:8761 ,界面如下:
因为没有服务注册,所以显示No instances available。
2.创建Eureka Client
创建一个新的SpringBoot项目,在pom.xml文件中加入Eureka依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>
在application.yml中添加配置:
eureka: client: serviceUrl: defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/ #将自己注册到Eureka上面去
开启客户端。同样,在入口类上添加@EnableDiscoveryClient注解即可开启Eureka客户端。
@SpringBootApplication @EnableDiscoveryClient public class ConfigServiceApplication { public static void main(String[] args) { SpringApplication.run(ConfigServiceApplication.class, args); } }
启动工程,再次访问http://localhost:8761,可以看到我们的服务被注册成功。