spring cloud 搭建流程记录

服务注册-EurekaServer (一)

2017-06-28  本文已影响0人  itfinally

spring cloud 是 spring 社区下的一套微服务解决方案,通过封装和整合 Netflix 公司的组件,简化并降低开发难度。

其中微服务需要有一个服务中心管理所有服务的状态,所有服务都要向该中心注册自身来实现服务发现,包括多个服务中心下( 配置高可用服务注册中心时 ),也需要相互注册。

euraka server 是服务中心的实现,maven 依赖如下:

<dependencies>
  <!-- 服务注册组件 -->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eurekaserver</artifactId>
  </dependency>
</dependencies>

application.properties 配置如下:

server.port = 10080
eureka.client.fetch-registry = false
eureka.client.register-with-eureka = false
eureka.client.serviceUrl.defaultZone = http://localhost:${server.port}/eureka/

eureka server 在启动之后会尝试注册自身,而
eureka.client.fetch-registry = falseeureka.client.register-with-eureka = false 两项配置是禁止这个行为。

完成上述配置后,启动一个 eureka server 只需要写几行代码启动即可:

@EnableEurekaServer
@SpringBootApplication
public class Application {

    public static void main( String[] args ) {
        new SpringApplicationBuilder( Application.class )
                .web( true )
                .run( args );
    }
}

然后编写一个客户端,maven 依赖如下:

<dependencies>
    <!-- spring boot -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- eureka 客户端组件 -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
  </dependencies>

写完依赖还没完,还有配置呢:

server.port = 12000
spring.application.name = SleepCare-TestingServices
eureka.client.serviceUrl.defaultZone = http://localhost:10080/eureka/

这里解释一下:

完成上述配置后,启动一个 eureka 客户端就像启动服务注册中心一样:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {

    public static void main( String[] args ) {
        new SpringApplicationBuilder( Application.class )
                .web( true )
                .run( args );
    }
}

注意这里用的是 @EnableDiscoveryClient注解,这个注解会开启自动注册功能,当然啦还会做其他事不过我还不清楚啦。换言之,用了这个注解,就是你只要躺着就好了,其他事人家来做。

到这里跑起来,如果控制台没有报错,那一般都是没什么大事的。
访问http://localhost:10080/( 我这里是这个地址,具体地址看你自己 )就会看到如下界面。

服务注册情况

图中的列表就是显示出当前注册到服务注册中心的服务啦,可以看到名为 SleepCare-TestingServices 的项目已经启动并注册了。其中 Appcalition 一项的名字对应的就是 spring.application.name 的属性值,并且一个名称可以对应多个 ip,这是高可用的配置,当然啦这是后话了。

当走到这一步还平平安安的,那都是已经成功搭起一个简单的注册中心和客户端了,这一篇先说这么多,喵。

上一篇 下一篇

猜你喜欢

热点阅读