springcloud(一)-集成Eureka 服务注册与发现(慕课网廖师兄SpringCloud微服务实战)

294 阅读1分钟

image.png

1.服务中心

  • 核心依赖

<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</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>
  • 启用Eureka Server

在启动类或者配置类上添加@EnableEurekaServer 注解

/**
 * Eureka 启动类
 * @author gaowenfeng
 *
 * @EnableEurekaServer  启用Eureka Server
 */
@SpringBootApplication
@EnableEurekaServer
public class MicroWeatherEurekaServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(MicroWeatherEurekaServerApplication.class, args);
	}
}
  • 配置

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    # 静止注册成客户端
    register-with-eureka: false
    fetch-registry: false
    # 服务的url
    service-url:
      defaultZone: http://{eureka.instance.hostname}:{server.port}/eureka
  • 检查

启动项目后访问 http://{host}:{serverport}

image.png

2. 服务注册

  • 核心依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </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>
  • 注册服务相关代码实现

启动类或者配置类添加@EnableDiscoveryClient注解

/**
 * 启动类
 * @author gaowenfeng
 */
@SpringBootApplication
@EnableDiscoveryClient
public class MsaWeatherCityServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(MsaWeatherCityServerApplication.class, args);
	}
}
  • 相关配置

spring:
  application:
    name: msa-weather-city-server

eureka:
    # 服务中心的url
    service-url:
      # 这里可以是一个数组,也就是可以注册多多个服务端,用逗号隔开
      defaultZone: http://localhost:8761/eureka/
      instance:
           # 自定义服务的域名
           hostname: clientName
server:
  port: 9991
  • 检查

启动实例,即可在服务中心界面以及控制台看到相关注册信息

image.png

  • Eureka高可用

image.png

让多个Eureka服务端两两注册,即一个Eureka做为另一个Eureka的客户端,然后让Client注册到每一个Eureka服务端上,这样,当一个服务端挂掉以后,在其他的Eureka服务端也可以发现注册的Client