[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兩個項目註冊成功
在這裏插入圖片描述

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