[SpringCloud]~Eureka(服务注册中心配置与使用)

简介

Eureka 是 Netflix 开发的,一个基于 REST 服务的,服务注册与发现的组件。
它主要包括两个组件:Eureka Server 和 Eureka Client。
Eureka Client(客户端):用于简化与 Eureka Server 的交互。
Eureka Server(注册中心):提供服务注册和发现的能力。

注册中心

第一步

新建一个SpringBoot项目,pom文件加入注册中心配置。

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

第二步

创建启动类,引入@EnableEurekaServer

package com.qy.test.eureka;

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

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

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

}

第三步

修改配置文件application.properties。

spring.application.name=eureka
server.port=8761
eureka.client.service-url.defaultZone=http://127.0.0.1:8761/eureka/
#表示是否将自己注册到Eureka Server上,默认为true
eureka.client.register-with-eureka=false
#表示是否从Eureka Server上获取注册信息,默认为true
eureka.client.fetch-registry=false
#设置清理的间隔时间
eureka.server.eviction-interval-timer-in-ms=6000
#关闭保护模式
eureka.server.enable-self-preservation=false

在这里插入图片描述

客户端

第一步

新建一个SpringBoot项目,pom文件加入客户端配置。

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

第二步

创建启动类,引入@EnableEurekaClient

package com.qy.test.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication(scanBasePackages = "com.qy.test.demo")
@EnableDiscoveryClient
@EnableEurekaClient
@Slf4j
public class DemoApplication {

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
		long time = (System.currentTimeMillis() - start)/1000;
		String info = "启动完成,耗时:%d秒,链接:http://%s:%s/swagger-ui.html";
		String port = ctx.getEnvironment().getProperty("server.port");
		String address = ctx.getEnvironment().getProperty("spring.cloud.client.ip-address");
		log.info(String.format(info,time,address,port));
	}

}

第三步

修改配置文件application.properties。

spring.application.name=demo
server.port=8001
eureka.client.service-url.defaultZone=http://127.0.0.1:8761/eureka/

在这里插入图片描述

使用

启动注册中心和客户端。
在这里插入图片描述
访问注册中心(一般默认路径 http://127.0.0.1:8761/)
demo、demo2两个项目注册成功
在这里插入图片描述

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