spring cloud 学习之 服务注册和发现(Eureka)

一:服务注册和发现(Eureka)

  1:采用Eureka作为服务注册和发现组件

  2:Eureka 项目中 主要在启动类加上 注解@EnableEurekaServer 

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

  3:eureka 是 一个高可用的组件,它没有后端缓存,每一个实例注册之后需要向注册中心发送心跳

在默认情况下erureka server也是一个eureka client ,必须要指定一个 server。eureka server的配置文件appication.yml

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

spring:
  application:
    name: eurka-server

  通过 eureka。client.registerWithEureka:false 和 fetchRegistry:false 来声明是eureka server

二:服务提供者(Eureka client)

  1:当client向server注册时,它会提供一些元数据,例如主机和端口,URL,主页等。Eureka server 从每个client实例接收心跳消息。

如果心跳超时,则通常将该实例从注册server中删除

  2:通过注解@EnableEurekaClient 表明自己是一个eurekaclient.

@SpringBootApplication
@EnableEurekaClient
@RestController
public class ServiceHiApplication {

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

    @Value("${server.port}")
    String port;

    @RequestMapping("/hi") public String home(@RequestParam(value = "name", defaultValue = "forezp") String name) { return "hi " + name + " ,i am from port:" + port; } }

  3:需要在配置文件中注明自己的服务注册中心地址,application.yml 配置文件

server:
  port: 8762

spring:
  application:
    name: service-hi

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

需要指明 spring.application.name 服务和服务之间的相互调用一般是根据name

  

猜你喜欢

转载自www.cnblogs.com/but009/p/9590216.html