SpringCloud Eureka Server/Client搭建

Eureka是SpringCloud Netflix提供的服務發現組件,本文介紹Eureka Server及Client的搭建步驟。

Eureka Server

創建Eureka Server項目

爲了方便起見,我們從Spring Initializr創建一個Eureka Server :
在這裏插入圖片描述
將得到的壓縮包解壓後導入到idea中。

配置application.properties

在application.properties中加入以下配置:

server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

logging.level.com.netflix.eureka=OFF
logging.level.com.netflix.discovery=OFF

增加@EnableEurekaServer註解

給程序入口類中加上@EnableEurekaServer,標記這是一個Euraka Server應用,如下:

 package com.example.eurekaserver;

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

@EnableEurekaServer
@SpringBootApplication
public class EurekaserverApplication {
	public static void main(String[] args) {
		SpringApplication.run(EurekaserverApplication.class, args);
	}
}

完成以上步驟,不出意外的化就可以把程序跑起來了

訪問Eureka Server

打開瀏覽器,輸入地址http://localhost:8761,出現以下界面則表示Eureka Server創建成功:
在這裏插入圖片描述

Eureka Client

創建Eureka Client項目

同樣,我們從Spring Initializr創建一個Eureka Client :
在這裏插入圖片描述

配置bootstrap.properties

創建bootstrap.properties配置文件,在文件中加入:

spring.application.name=a-bootiful-client

編寫EurekaclientApplication.java

將Spring initializr默認生成的EurekaclientApplication.java替換成以下內容:

package com.example.eurekaclient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaclientApplication {

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

@RestController
class ServiceInstanceRestController {

	@Autowired
	private DiscoveryClient discoveryClient;

	@RequestMapping("/service-instances/{applicationName}")
	public List<ServiceInstance> serviceInstancesByApplicationName(
			@PathVariable String applicationName) {
		return this.discoveryClient.getInstances(applicationName);
	}
}

完成上述步驟便可以運行該應用

訪問Eureka Client

打開瀏覽器,輸入地址http://localhost:8080/service-instances/a-bootiful-client,可以看到一下界面:
在這裏插入圖片描述

在Eureka Server上查看Client的信息

在這裏插入圖片描述

參考資料

https://spring.io/guides/gs/service-registration-and-discovery/

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