Eureka介绍
Spring Cloud Eureka 是 Spring Cloud Netflix 微服务套件的一部分,基于 Netflix Eureka 做了二次封装,主要负责完成微服务架构中的服务治理功能。
除了用Eureka来做注册中心,我们还可以使用Consul,Etcd,Zookeeper等等来作为服务的注册中心。
有用过dubbo的同学应该清楚,dubbo中也有几种注册中心,有基于Zookeeper的,有基于redis的等等,用的最多的还是Zookeeper方式。
至于使用哪种方式,其实都是可以的,注册中心无非就是管理所有服务的信息和状态。
用我们生活中的列子来说明的话,我觉得12306比较合适。
首先12306就好比一个注册中心,N量火车都注册在了12306上面,我们顾客就好比调用的客户端,当我们需要坐火车时,我们会去12306上看有没有票,有票就可以购买,然后拿到火车的班次,时间等等,最后出发。
程序也是一样,当你需要调用某一个服务的时候,你会先去Eureka中去拉取服务列表,查看你调用的服务在不在其中,在的话就拿到服务地址,端口,等等信息,然后调用。
注册中心带来的好处就是你不需要知道有多少提供方,你只需要关注注册中心即可,你不必关系有多少火车在运行,你只需要去12306上看有没有票可以买就可以。
Spring Cloud中使用Eureka
- 首先创建一个maven工程(或者用http://start.spring.io/来创建一个spring cloud项目)
- 在pom.xml增加依赖(如果下载包特别慢可以考虑使用阿里云的maven镜像服务器)
<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.ppl</groupId> <artifactId>ppl-eureka</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ppl-eureka</name> <!-- Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> </dependencies> <!-- Spring Cloud --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR4</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
- 接着创建一个启动类
package com.ppl.eureka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * 服务注册中心 * @author ljl * */ @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }编写配置文件application.yml
server: port: 8888 #应用的名字 spring: application: name: ppl-eureka eureka: instance: hostname: localhost client: registerWithEureka: false # 由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己 fetchRegistry: false # 由于注册中心的职责就是维护服务实例,他并不需要去检索服务,所以也设置为false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
更多教程请关注: