Spring Cloud Eureka 初探

Eureka介绍

Spring Cloud Eureka 是 Spring Cloud Netflix 微服务套件的一部分,基于 Netflix Eureka 作了二次封装,主要负责完成微服务架构中的服务治理功能。git

除了用Eureka来作注册中心,咱们还可使用Consul,Etcd,Zookeeper等等来做为服务的注册中心。github

有用过dubbo的同窗应该清楚,dubbo中也有几种注册中心,有基于Zookeeper的,有基于redis的等等,用的最多的仍是Zookeeper方式。redis

至于使用哪一种方式,其实都是能够的,注册中心无非就是管理全部服务的信息和状态。spring

用咱们生活中的列子来讲明的话,我以为12306比较合适。服务器

首先12306就比如一个注册中心,N量火车都注册在了12306上面,咱们顾客就比如调用的客户端,当咱们须要坐火车时,咱们会去12306上看有没有票,有票就能够购买,而后拿到火车的班次,时间等等,最后出发。架构

程序也是同样,当你须要调用某一个服务的时候,你会先去Eureka中去拉取服务列表,查看你调用的服务在不在其中,在的话就拿到服务地址,端口,等等信息,而后调用。app

注册中心带来的好处就是你不须要知道有多少提供方,你只须要关注注册中心便可,你没必要关系有多少火车在运行,你只须要去12306上看有没有票能够买就能够。maven

Spring Cloud中使用Eureka

<!-- Spring Boot -->
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath />
</parent>
<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.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>
  • 接着建立一个启动类
/**
 * 服务注册中心
 * 
 * @author yinjihuan
 *
 */
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
    
}
  • 编写配置文件application.properties
server.port=8761
spring.application.name=fangjia-eureka
eureka.instance.hostname=localhost
# 因为该应用为注册中心,因此设置为false,表明不向注册中心注册本身
eureka.client.register-with-eureka=false
# 因为注册中心的职责就是维护服务实例,他并不须要去检索服务,因此也设置为false
eureka.client.fetch-registry=false
# 关闭自我保护
eureka.server.enableSelfPreservation=false

最后启动EurekaServerApplication,访问http://localhost:8761/就能够打开管理页面了。spring-boot

具体代码能够参考个人github:微服务

https://github.com/yinjihuan/spring-cloud

相关文章
相关标签/搜索