快速搭建微服务-注册中心、服务发现

注册中心是微服务的核心组件,SpringCloud比较常见的注册中心有eureka和consul,这里简单说明下这两种注册中心服务如何实现。这里的例子是基于SpringCloud Edgeware版本。

Spring Cloud Eureka注册中心

Server端

  • maven

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
  • application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    server:
    port: 9101
    eureka:
    instance:
    hostname: localhost
    client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
    defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka
    server:
    wait-time-in-ms-when-sync-empty: 0
    spring:
    application:
    name: eureka-server
  • Application.java

    1
    2
    3
    4
    5
    6
    7
    @EnableEurekaServer
    @SpringBootApplication
    public class EurekaServerApplication {
    public static void main(String[] args) {
    SpringApplication.run(EurekaServerApplication.class, args);
    }
    }

Client端

  • maven

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
  • application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    server:
    port: 9110
    eureka:
    client:
    service-url:
    defaultZone: http://eureka-server:9101/eureka
    instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
    spring:
    application:
    name: service-order
  • Application.java

    1
    2
    3
    4
    5
    6
    7
    @EnableDiscoveryClient
    @SpringBootApplication
    public class ServiceOrderApplication {
    public static void main(String[] args) {
    SpringApplication.run(ServiceOrderApplication.class, args);
    }
    }

Spring Cloud Consul注册中心

Server端

  1. 下载consul服务端程序

  2. 运行consul

    • 开发环境

      1
      consul agent -dev
    • 正式部署

      1
      consul agent -data-dir=tem/consul

Client端

  • maven

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
    </dependency>
  • application.yml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    server:
    port: 9110
    spring:
    application:
    name: service-order
    cloud:
    consul:
    host: localhost
    port: 8500
  • Application.java

    1
    2
    3
    4
    5
    6
    7
    @EnableDiscoveryClient
    @SpringBootApplication
    public class ServiceOrderApplication {
    public static void main(String[] args) {
    SpringApplication.run(ServiceOrderApplication.class, args);
    }
    }