SpringCloud 3 Service Provider

上一章已经建好了Eureka Server

 

这是还没有应用来注册这时我们新建一个服务提供者 cloud-hello

 

新建过程不再重复,和创建eureka server的过程一样。

 

在启动类上加@EnableEurekaClient 注解。服务即会想注册中心注册。

 

@EnableEurekaClient
@SpringBootApplication
public class CloudHelloApplication {

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

}

 

添加一个restfull接口类

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String helloCloud(){
        return "hello cloud";
    }
}

 

添加配置文件 application.yml

server:
  port: 8889

spring:
  application:
    name: hello-service

eureka:
  client:
    healthcheck:
      enabled: true
    service-url:
      defaultZone: http://localhost:8888/eureka/
  instance:
    prefer-ip-address: true
    instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}}
    metadata-map:
      zone: ABC      # eureka可以理解的元数据
      lilizhou: BBC  # 不会影响客户端行为
    lease-renewal-interval-in-seconds: 5

eureka.client.healthcheck.enabled = true 开启Eureka客户端的健康检查
eureka.client.service-url.defaultZone 指定客户端对应的注册中心服务器的地址
eureka.instance.prefer-ip-address = true 表示注册到注册中心的是IP    
eureka.instance.instance-id 表示注册到注册中心实例的ID规则

eureka.instance.lease-renewal-interval-in-seconds 表示续约更新时间间隔,也就是客户端健康检查的心跳时间间隔。

注意 ${spring.cloud.client.ip-address} 需添加 

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-commons</artifactId>
        </dependency>

可以放到父项目

 

遇到的坑及解决:服务并没有像注册中心注册

 

去官网看资料 https://spring.io/projects/spring-cloud-netflix#overview

 

客户端只说了使用注解,并没讲用什么依赖,查的别人的博客都是spring-cloud-starter-netflix-eureka-client

然后服务端是用  @EnableEurekaServer 和依赖 spring-cloud-starter-netflix-eureka-server

 

最后实验发现客户端并不需要 spring-cloud-starter-netflix-eureka-client 依赖,

同样使用spring-cloud-starter-netflix-eureka-server 依赖配合 @EnableEurekaClient注解即可实现客户端。

改好依赖后重启cloud-hello,服务已在注册中心注册了。

 

 

这样看来spring-cloud-starter-netflix-eureka-server 这个依赖是所有服务都需要的,可以抽到父项目中。

 

本地开发小技巧:由于eureka自我保护机制的工作机制是如果在15分钟内超过85%的客户端节点都没有正常的心跳,那么Eureka就认为客户端与注册中心出现了网络故障,Eureka Server自动进入自我保护机制。但是由于在本地开发很容易15分钟内超过85%的客户端节点心跳正常,如果还保活会造成服务已经关闭了,结果注册中心状态还是可用的假象。

这是需要在服务端关闭保活

服务端

eureka:

  server:

    # 测试时关闭自我保护机制,保证不可用服务及时踢出

    enable-self-preservation: false

 

客户端:

# 心跳检测检测与续约时间

# 测试时将值设置设置小些,保证服务关闭后注册中心能及时踢出服务

eureka:

  instance:

    lease-renewal-interval-in-seconds: 1

    lease-expiration-duration-in-seconds: 2

    #lease-renewal-interval-in-seconds 每间隔1s,向服务端发送一次心跳,证明自己依然”存活“

    #lease-expiration-duration-in-seconds  告诉服务端,如果我2s之内没有给你发心跳,就代表我“死”了,将我踢出掉。

这样的或服务注册中心的服务就是实时得了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章