这里咱们会用到Spring Cloud Netflix,该项目是Spring Cloud的子项目之一,主要内容是对Netflix公司一系列开源产品的包装,它为Spring Boot应用提供了自配置的Netflix OSS整合。经过一些简单的注解,开发者就能够快速的在应用中配置一下经常使用模块并构建庞大的分布式系统。它主要提供的模块包括:服务发现(Eureka),断路器(Hystrix),智能路有(Zuul),客户端负载均衡(Ribbon)等。git
因此,咱们这里的核心内容就是服务发现模块:Eureka。下面咱们动手来作一些尝试。spring
建立一个基础的Spring Boot工程,并在pom.xml
中引入须要的依赖内容:apache
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.clc</groupId> <artifactId>registry</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>registry</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> </project>
经过@EnableEurekaServer
注解启动一个服务注册中心提供给其余应用进行对话。这一步很是的简单,只须要在一个普通的Spring Boot应用中添加这个注解就能开启此功能,好比下面的例子:app
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class RegistryApplication { public static void main(String[] args) { SpringApplication.run(RegistryApplication.class, args); } }
在默认设置下,该服务注册中心也会将本身做为客户端来尝试注册它本身,因此咱们须要禁用它的客户端注册行为,只须要在application.properties
中问增长以下配置:负载均衡
#服务端口 server.port=9001 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
启动工程后,访问:http://localhost:9001/maven
至此,注册中心搭建完成分布式
工程地址-https://gitee.com/chengluchao/clc__registryspring-boot