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/

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