Spring Cloud register-server(eur

2018-02-27  本文已影响0人  Lano_chazz

基本架构

主要包含三个组件:Eureka Server、Service Provider、Service Consumer。

Service Provider会向Eureka Server做Register(服务注册)、Renew(服务续约)、Cancel(服务下线)等操作。
Eureka Server之间会做注册服务的同步,从而保证状态一致
Service Consumer会向Eureka Server获取注册服务列表,并消费服务

Eureka Server

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {
  public static void main(String[] args) {
    SpringApplication.run(EurekaServiceApplication.class, args);
  }
}

Service Provider

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
@EnableDiscoveryClient
@SpringBootApplication
public class ReservationServiceApplication {
  public static void main(String[] args) {
    new SpringApplicationBuilder(ReservationServiceApplication.class)
            .run(args);
  }
}

Service Consumer

@EnableDiscoveryClient
@SpringBootApplication
public class ReservationClientApplication {
  @Bean
  CommandLineRunner runner(DiscoveryClient dc) {
    return args -> {
      dc.getInstances("reservation-service")
              .forEach(si -> System.out.println(String.format(
                      "Found %s %s:%s", si.getServiceId(), si.getHost(), si.getPort())));
    };
  }
  public static void main(String[] args) {
    SpringApplication.run(ReservationClientApplication.class, args);
  }
}
eureka.server.peerEurekaNodesUpdateIntervalMs

Service Consumer在启动时会从Eureka Server获取所有服务列表,并在本地缓存。需要注意的是,需要确保配置eureka.client.shouldFetchRegistry=true。

由于在本地有一份缓存,所以需要定期更新,定期更新频率可以通过eureka.client.registryFetchIntervalSeconds配置。

其他配置信息

#单例模式启动Eureka Server
server:
  port: 8761 #启动端口
eureka:
  client:
    registerWithEureka: false #false:不作为一个客户端注册到注册中心   
    fetchRegistry: false #为true时,可以启动,但报异常:Cannot execute request on any known server
zuul:
  prefix: /techouse #为zuul设置一个公共的前缀
  #ignoredServices: '*'
  routes:
    cloud-client: #随便定义,当不存在serviceId时,默认该值为serviceId(就是注册服务的名称,属性spring.application.name)
      path: /usersystem/** #匹配/techouse/usersystem/** 均路由到cloud-client
      serviceId: cloud-client #指定路由到的serviceId
ribbon:
  eureka:
    enabled: false #配置zuul路由时用将此属性设置为false

cloud-client:
  ribbon:
    listOfServers: 127.0.0.1:8800 #为cloud-client服务指定一组服务地址,应该是用于负载均衡
上一篇下一篇

猜你喜欢

热点阅读