服务注册与发现

服务发现

​ 服务消费者和服务提供者在启动的时候将地址写入到服务注册中心

服务注册表

​ 包含了服务实例的网络地址的数据库。

private final ConcurrentHashMap<String, Map<String, Lease<InstanceInfo>>> registry = new ConcurrentHashMap();

​ 维护注册表、拉取注册表、更新心跳时间,全部发生在内存里。

服务发现方式
1)客户端服务发现模式
2)服务端服务发现模式
心跳机制

​ 每个Eureka Client每隔30秒会发送一次心跳到Eureka Server,通知该服务还存活。如果某个Eureka超过3次(90s)没有发送请求到Eureka,那么该服务就已经挂掉了,将会被Erueka踢除。

实现EruekaService
1)pom
<!--引入SpringCloud、eureka-server依赖-->
<!--注意版本兼容性-->
<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2)启动类标注:EnableEurekaServer(告知是EurekaServer)

@SpringBootApplication
@EnableEurekaServer
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class MicroserviceEurekaApplication {

    public static void main(String[] args) {
        SpringApplication.run(MicroserviceEurekaApplication.class, args);
    }

}

3)配置EurekaServer

server:
  port: 8761
eureka:
  client:
    #是否从Eureka Server获取注册信息,默认为true。 如果这是一个单点的EurekaServer,不需要同步其他节点的数据,可以设为false
    fetch-registry: false
    #是否将自己注册到Eureka Server, 默认为true。 由于当前应用就是EurekaServer,因此设为 false
    register-with-eureka: false
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka/
注册服务到Erueka

1)配置erueka

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
    fetchRegistry: false
  instance:
    prefer-ip-address: true
    instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}

2)开启erueka客户端

@SpringBootApplication
@EnableEurekaClient
public class MicroserviceProviderUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(MicroserviceProviderUserApplication.class, args);
    }

}

转载于:https://my.oschina.net/javaLin/blog/3059654

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值