创建服务提供者

概述

当Eureka Client向Eureka Server注册时,它会提供一些元数据,例如主机和端口,URL,主页等。Eureka Server从每个Client实例接受心跳信息。如果心跳超时,则通常将该实例从注册Server剔除。

POM


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

Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaProviderApplication {

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

Application.yml

server:
port: 8089

eureka:
client:
  serviceUrl:
    defaultZone: http://localhost:1111/eureka/
instance:
  lease-renewal-interval-in-seconds: 10 #服务续约(默认30s)
  lease-expiration-duration-in-seconds: 15 #服务剔除>服务续约时间(默认90s)
  hostname: localhost
  instance-id: ${spring.application.name}:${server.port}

spring:
application:
  name: eureka-provider
management:
security:
  enabled: false #spring boot actuator#端点监控安全是否启用属性

注意: 需要指明 spring.application.name,这个很重要,这在以后的服务与服务之间相互调用一般都是根据这个 name 。从时间上来算,Eureka注册中心剔除一个失效服务需要3分钟,

客户端服务续约时间(30s)+客户端服务剔除时间(90s)+剔除失效服务时间(60s)=180秒

Controller

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class HelloController {

   public static final String HELLO_WORLD = "Hello World!";
   
//spring cloud 1.2.0
   @Resource
   private Registration registration;

   @Autowired
   private ServiceRegistry serviceRegistry;

   /**
    * test eureka-client-ribbon model ribbon retry
    * <br/>
    **/
   @GetMapping("/hello")
   public String index() {
       log.info("load balanced service instance meta: {}", registration.getMetadata());
       log.info("load balanced host: {},port: {},service id: {}", registration.getHost(), registration.getPort(), registration.getServiceId());
       log.info("service id: {}", registration.getServiceId());
       log.info("service registry: {}", serviceRegistry.getStatus(registration));
       return HELLO_WORLD;
  }

}

启动工程,打开http://localhost:1111/,即为Eureka Server的网址

 

原文地址:https://www.cnblogs.com/liuenyuan1996/p/10282626.html