文章目录
微服务架构现在已经是各个互联网应用的标配,并且开始作为一个技术框架的基本要求,慢慢扩展到其他行业,比如金融,保险等面向大量用户的J2EE应用中。使用微服务架构,就意味着我们需要将原本高度耦合在同一个应用中的多个功能拆分出来,解耦为多个微服务应用,并且,每个微服务应用可单独编译,集成,部署。因此,每个微服务可能在生态系统中具有多个实例,并且数量和实例地址都是动态变化的。这里,就对APM的分布式追踪提出了具体的要求,即单笔业务,在微服务架构下,会经过多个步骤,是多个原子服务聚合后的结果,APM需要对整个链路上的各个服务的性能进行监控,并归纳到单个业务当中。下图,是一张互联网通用的架构图,其中每个环节都是微服务的核心部分,由此可见,分布式追踪已经成为APM必不可少的功能。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190218150444399.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTM2MTM0Mjg=,size_16,color_FFFFFF,t_70)
在上一篇文章 elastic APM 深入测试 一 (无嵌套调用的分布式微服务监控) 中,我们已经初探了使用 传统的服务器端负载平衡的分布式模型的分布式追踪。在文章 Spring cloud 之ribbon与eureka – 发生在客户端的负载均衡中,我也解释了传统的服务器端负载平衡所具有的问题,在这篇博文中,我将选择spring cloud,作为基本的微服务架构来对elastic APM的distributed trace功能进行深入的测试。
测试的基本架构
技术栈
我们选用如下技术栈:
- Java,IntelliJ,Maven作为开发环境
- Spring-boot和Cloud作为应用程序框架
- Eureka作为服务注册服务器
- 使用OpenFeign作为服务发现和远程调用的客户端
测试框架逻辑拓扑
以下,是spring cloud使用Eureka作为注册中心的基本通信图
我们将简单搭建类似的应用拓扑:
- 创建一个Eureka server作为服务的注册和发现中心
- 创建多个provider实例,注册到服务中心,并行的提供服务
- 创建一个consumer应用,通过服务中心提供的信息,远程调用provider实例提供的服务
微服务应用的搭建
搭建Eureka注册服务器
访问 https://start.spring.io/,创建一个Spring引导项目,将Eureka Server作为依赖项:
Eureka服务器配置
在spring boot应用程序类中添加@EnableEurekaServer
注解,并在应用程序属性文件中添加以下配置。
package com.example.ribboneurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class RibbonEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonEurekaServerApplication.class, args);
}
}
application.properties:
spring.application.name= ${springboot.app.name:eureka-serviceregistry}
server.port = ${server-port:8761}
eureka.instance.hostname= ${springboot.app.name:eureka-serviceregistry}
eureka.client.registerWithEureka= false
eureka.client.fetchRegistry= false
eureka.client.serviceUrl.defaultZone: http://${registry.host:localhost}:${server.port}/eureka/
创建provider service
和之前一样,在spring initializer上创建一个项目,包含spring-boot-web和eureka discovery依赖项。web用于提供restful API, eureka discovery用于往eureka server上注册服务。
创建 rest endpoint
实现一个 Rest Controller,提供rest endpoint,用于对数据库的操作:
package com.example.sqldemo.controller;
import com.example.sqldemo.entity.User;
import com.example.sqldemo.service.UserService;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List