Spring Cloud微服务解决方案 ②:注册服务到Eureka上

首先你的把上一篇文章中的Eureka服务启动起来,源码地址:https://download.csdn.net/download/qq_22075041/10851487

本文对应microservice-consumer-movie和microservice-provider-user子模块,他俩为调用关系,作为Eureka客户端的话,配置一样,只是为后文做铺垫。以下是microservice-provider-user模块为例。

1.首先是pom依赖

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
        <!--actuator是监控系统健康情况的工具-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

2.启动类上加一个注解@EnableEurekaClient,注意他是 org.springframework.cloud.netflix.eureka.EnableEurekaClient下;还有一个注解@EnableDiscoveryClient,感兴趣的可以了解一下他俩之间的区别

package com.itmuch.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class MicroserviceSimpleProviderUserApplication {

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

最重要的还是application.yml总得配置

server:
  port: 7900
spring:
  jpa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:
    platform: h2
    schema: classpath:schema.sql
    data: classpath:data.sql
  application:
    name: microservice-provider-user #服务的名称 在eureka服务上会全大写显示
logging:
  level:
    root: INFO
    org.hibernate: INFO
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
    com.itmuch: DEBUG
eureka:
  client:
    healthcheck: 
      enabled: true # 心跳检测
    serviceUrl:
      defaultZone: http://user:password123@localhost:8761/eureka #注册到这个地址
  instance:
    prefer-ip-address: true # 显示IP地址
    # 名称规则    服务名:ip:端口
    instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
    metadata-map:
      zone: ABC      # eureka可以理解的元数据
      lilizhou: BBC  # 不会影响客户端行为
    lease-renewal-interval-in-seconds: 5

启动起来可以去eureka服务端查看到这个服务注册上去了,请求UserController下的这俩个接口对比一下

  @GetMapping("/eureka-instance")
  public String serviceUrl() {
    InstanceInfo instance = this.eurekaClient.getNextServerFromEureka("MICROSERVICE-PROVIDER-USER", false);
    return instance.getHomePageUrl();
  }

  @GetMapping("/instance-info")
  public ServiceInstance showInfo() {
    ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
    return localServiceInstance;
  }

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页