Spring Cloud Eureka 初探

时间:2022-05-06
本文章向大家介绍Spring Cloud Eureka 初探,主要内容包括Eureka介绍、Spring Cloud中使用Eureka、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

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镜像服务器http://cxytiandi.com/blog/detail/5321)
<!-- 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/就可以打开管理页面了。

具体代码可以参考我的github:

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