服务注册与发现
这里我们会用到,该项目是Spring Cloud的子项目之一,主要内容是对Netflix公司一系列开源产品的包装,它为Spring Boot应用提供了自配置的Netflix OSS整合。通过一些简单的注解,开发者就可以快速的在应用中配置一下常用模块并构建庞大的分布式系统。它主要提供的模块包括:服务发现(Eureka),断路器(Hystrix),智能路有(Zuul),客户端负载均衡(Ribbon)等。
所以,我们这里的核心内容就是服务发现模块:Eureka。下面我们动手来做一些尝试。
创建“服务注册中心”
创建一个基础的Spring Boot工程,并在pom.xml
中引入需要的依赖内容:
4.0.0 com.clc registry 0.0.1-SNAPSHOT jar registry Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.3.5.RELEASE org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-eureka-server org.springframework.cloud spring-cloud-dependencies Brixton.RELEASE pom import
通过@EnableEurekaServer
注解启动一个服务注册中心提供给其他应用进行对话。这一步非常的简单,只需要在一个普通的Spring Boot应用中添加这个注解就能开启此功能,比如下面的例子:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@EnableEurekaServer@SpringBootApplicationpublic class RegistryApplication { public static void main(String[] args) { SpringApplication.run(RegistryApplication.class, args); }}
在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为,只需要在application.properties
中问增加如下配置:
#服务端口server.port=9001eureka.client.register-with-eureka=falseeureka.client.fetch-registry=falseeureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
启动工程后,访问:
至此,注册中心搭建完成
工程地址-
posted @ 2018-08-30 17:03 阅读( ...) 评论( ...)