演示项目源码下载:(访问密码:9987)
Spring-Cloud-discovery-server.zip
了解如何创建微服务的基础上,Spring Cloud,对Netflix的Eureka注册表服务器以及如何等微服务(Eureka客户端)使用它来注册和发现服务来调用其API。
我们将使用基于 Spring Boot 的 Spring Cloud API。我们将使用 Netflix Eureka 服务器来构建服务注册服务器和 Eureka 客户端,这些客户端将自行注册并发现其他服务以调用 REST API。
我们将为这个Netflix Eureka 示例创建三个微服务。
这是上面列出的三个服务之间的交互图。
正如我们现在所知,围绕微服务有很多动力。从单体架构到基于微服务的架构的转变在可维护性、可扩展性、高可用性等方面为未来带来了许多好处。然而,与此同时,在进行这种迁移时也存在许多挑战。其中之一是维护单个微服务地址。这项任务可能非常复杂——取决于服务的数量及其动态性质。如果整个基础设施是分布式的并且还有一些复制,那么维护这个服务地址就会变得更加困难。
为了解决这个问题,在分布式计算中有一个称为“服务注册和发现”的概念,其中一个专用服务器负责维护所有已部署和删除的微服务的注册表。这将充当所有其他应用程序/微服务的电话簿。
将其视为一种查找服务,微服务(客户端)可以在其中注册自己并发现其他已注册的微服务。当客户端微服务向 Eureka 注册时,它会提供元数据,例如主机、端口和健康指标,从而允许其他微服务发现它。发现服务器期望来自每个微服务实例的常规心跳消息。如果实例开始始终无法发送心跳,则发现服务器将从其注册表中删除该实例。这样我们就会有一个非常稳定的微服务生态系统相互协作,而且我们不需要手动维护其他微服务的地址,如果扩容/缩容非常频繁,这几乎是不可能完成的任务,按需,我们使用虚拟主机专门在云环境中托管服务。
按照以下步骤创建和运行 Eureka 服务器。
从Spring Boot 初始值设定项门户创建一个具有两个依赖项的 Spring boot 项目,即Eureka server
和Actuator
。给出其他maven GAV坐标并下载项目。
解压缩该项目并将其作为现有的 maven 项目导入 Eclipse。在这一步中,所有必需的依赖项都将从 maven 存储库下载。
现在SpringEurekaServerApplication
在下载的项目中打开spring已经生成的类,并@EnableEurekaServer
在类上添加注释。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class SpringEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringEurekaServerApplication.class, args);
}
}
再次构建项目。有了这个注解,这个工件就会像微服务注册中心和发现服务器一样工作。
创建一个application.yml
在src\main\resources
目录中调用的文件。添加这些属性 -
server:
port: ${PORT:8761} # Indicate the default PORT where this service will be started
eureka:
client:
registerWithEureka: false #telling the server not to register himself in the service registry
fetchRegistry: false
server:
waitTimeInMsWhenSyncEmpty: 0 #wait time for subsequent sync
创建另一个bootstrap.yml
在src\main\resources
目录中调用的文件。添加这些属性 -
spring:
application:
name: eureka
cloud:
config:
uri: ${CONFIG_SERVER_URL:http://localhost:8888}
将应用程序作为 Spring Boot 应用程序启动。打开浏览器并转到http://localhost:8761/
,您应该会看到如下所示的 eureka 服务器主页
请注意,此时此处没有注册服务,这是预期的,一旦我们启动客户端服务,该服务器将自动更新客户端服务的详细信息。
按照以下步骤创建和运行运行学生服务的 Eureka 客户端。
从具有四个依赖项的初始化程序门户创建一个 Spring boot 项目,即Actuator
、Web
、Rest Repositories
、Eureka Discovery
。给出其他maven GAV坐标并下载项目。
解压缩该项目并将其作为现有的 maven 项目导入 Eclipse。
现在@EnableEurekaClient
在src
文件夹中存在的 Spring boot 应用程序类上添加注释。有了这个注解,这个工件将像一个 spring 发现客户端一样,并将在附加到这个服务的Eureka服务器中注册自己。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringEurekaClientStudentServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SpringEurekaClientStudentServiceApplication.class, args);
}
}
创建一个application.yml
在src\main\resources
目录中调用的文件并添加以下行。
server:
port: 8098 #default port where the service will be started
eureka: #tells about the Eureka server details and its refresh time
instance:
leaseRenewalIntervalInSeconds: 1
leaseExpirationDurationInSeconds: 2
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
healthcheck:
enabled: true
lease:
duration: 5
spring:
application:
name: student-service #current service name to be used by the eureka server
management:
security:
enabled: false #disable the spring security on the management endpoints like /env, /refresh etc.
logging:
level:
com.example.howtodoinjava: DEBUG
现在添加一个RestController
并公开一个 rest 端点,用于获取特定学校的所有学生详细信息。在这里,我们公开/getStudentDetailsForSchool/{schoolname}
端点以服务于业务目的。为简单起见,我们对学生的详细信息进行了硬编码。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.howtodoinjava.springeurekaclientstudentservice.domain.Student;
@RestController
public class StudentServiceController {
private static Map<String, List<Student>> schooDB = new HashMap<String, List<Student>>();
static {
schooDB = new HashMap<String, List<Student>>();
List<Student> lst = new ArrayList<Student>();
Student std = new Student("Sajal", "Class IV");
lst.add(std);
std = new Student("Lokesh", "Class V");
lst.add(std);
schooDB.put("abcschool", lst);
lst = new ArrayList<Student>();
std = new Student("Kajal", "Class III");
lst.add(std);
std = new Student("Sukesh", "Class VI");
lst.add(std);
schooDB.put("xyzschool", lst);
}
@RequestMapping(value = "/getStudentDetailsForSchool/{schoolname}", method = RequestMethod.GET)
public List<Student> getStudents(@PathVariable String schoolname) {
System.out.println("Getting Student details for " + schoolname);
List<Student> studentList = schooDB.get(schoolname);
if (studentList == null) {
studentList = new ArrayList<Student>();
Student std = new Student("Not Found", "N/A");
studentList.add(std);
}
return studentList;
}
}
Student
class 是一个简单的 POJO。
public class Student
{
private String name;
private String className;
public Student(String name, String className) {
super();
this.name = name;
this.className = className;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
将此项目作为 Spring Boot 应用程序启动。现在验证该服务是否已自动注册到 Eureka 服务器中。转到 Eureka 服务控制台并刷新页面。现在如果一切顺利,我们将在 eureka 服务控制台中看到一个关于student-service 的条目。这表明 Eureka 服务器和客户端都知道彼此。
我们现在将验证/getStudentDetailsForSchool/{schoolname}
端点是否已启动并正在运行。转到浏览器并转到http://localhost:8098/getStudentDetailsForSchool/abcschool
,它将提供特定学校的学生详细信息abcschool
。
现在我们将创建学校服务,它将自己注册到Eureka服务器——它将发现和调用学生服务,而无需硬编码的 URL 路径。
按照创建学生服务的确切步骤,创建和运行运行学校服务的 Eureka 客户端。
从具有四个依赖项的初始化程序门户创建一个 Spring boot 项目,即Actuator
、Web
、Rest Repositories
、Eureka Discovery
。给出其他maven GAV坐标并下载项目。
解压缩该项目并将其作为现有的 maven 项目导入 Eclipse。
现在@EnableEurekaClient
在src
文件夹中存在的 Spring boot 应用程序类上添加注释。有了这个注解,这个工件将像一个 spring 发现客户端一样,并将在附加到这个服务的Eureka服务器中注册自己。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringEurekaClientSchoolServiceApplication {
public static void main(String[] args) {
SpringApplication.run(SpringEurekaClientSchoolServiceApplication.class, args);
}
}
创建一个application.yml
在src\main\resources
目录中调用的文件并添加以下行。除了端口号和服务名称外,这些配置与学生服务非常相似。
server:
port: 9098 #port number
eureka:
instance:
leaseRenewalIntervalInSeconds: 1
leaseExpirationDurationInSeconds: 2
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
healthcheck:
enabled: true
lease:
duration: 5
spring:
application:
name: school-service #service name
logging:
level:
com.example.howtodoinjava: DEBUG
现在添加一个RestController
并公开一个休息端点以获取学校详细信息。此端点将使用使用应用程序名称的服务发现样式 URL,而不是带有 host:port 的完整 URL。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class SchoolServiceController {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/getSchoolDetails/{schoolname}", method = RequestMethod.GET)
public String getStudents(@PathVariable String schoolname)
{
System.out.println("Getting School details for " + schoolname);
String response = restTemplate.exchange("http://student-service/getStudentDetailsForSchool/{schoolname}",
HttpMethod.GET, null, new ParameterizedTypeReference<String>() {}, schoolname).getBody();
System.out.println("Response Received as " + response);
return "School Name - " + schoolname + " \n Student Details " + response;
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
这样我们就可以摆脱特定的服务配置,我们可以将服务查找责任交给Eureka服务器和这里提供的休息模板。@LoadBalanced
如果多个实例正在为同一服务运行,我们也可以在此处应用负载平衡(请参阅注释)。
我们使用的 URL 是http://student-service/getStudentDetailsForSchool/{schoolname}
. 显然,我们只使用服务名称student-service
来代替host:port
. 这将由 spring 框架、eureka 服务器和 rest 模板一起在内部处理。
现在也开始学校服务。所有三个服务都已启动。检查Eureka服务器控制台。学生和学校服务都必须在那里注册。
转到浏览器并转到 http://localhost:9098//getSchoolDetails/abcschool,它将提供特定学校abcschool详细信息的学校详细信息。我们在内部调用了学生服务。响应在浏览器中将如下所示:
@EnableEurekaServer
和@EnableEurekaClient
是应用生态系统的心脏。没有这两件事就根本行不通。我们看到了可以轻松高效地部署服务注册中心和发现服务器以及客户端。Spring 框架在内部维护了很多东西。在这里,我们只是使用几个注释和非常少的配置来快速完成整个事情。
演示项目源码下载:(访问密码:9987)
Spring-Cloud-discovery-server.zip
https://www.leftso.com/article/861.html