Spring Cloud Skywalking集成

Posted 我是廖志伟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Cloud Skywalking集成相关的知识,希望对你有一定的参考价值。

主项目链接:https://gitee.com/java_wxid/java_wxid
项目架构及博文总结:

项目模块:
前期规划,实现部分

java_wxid   
├── demo                                                            // 演示模块
│     └── 模块名称:apache-mybatis-demo模块                            //Apache Mybatis集成(已实现并有博文总结)
│     └── 模块名称:apache-shardingsphere-demo模块                     //Apache ShardingSphere集成(已实现并有博文总结)
│     └── 模块名称:design-demo模块                                    //设计模式实战落地(已实现并有博文总结)
│     └── 模块名称:elasticsearch-demo模块                             //ElasticSearch集成(已实现并有博文总结)
│     └── 模块名称:mongodb-demo模块                                   //MongoDB集成(已实现并有博文总结)
│     └── 模块名称:redis-demo模块                                     //Redis集成(已实现并有博文总结)
│     └── 模块名称:spring-boot-demo模块                               //Spring Boot快速构建应用(已实现并有博文总结)
│     └── 模块名称:spring-cloud-alibaba-nacos-demo模块                //Spring Cloud Alibaba Nacos集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-alibaba-seata-demo模块                //Spring Cloud Alibaba Seata集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-alibaba-sentinel-demo模块             //Spring Cloud Alibaba Sentinel集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-gateway-demo模块                      //Spring Cloud Gateway集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-hystrix-demo模块                      //Spring Cloud Hystrix集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-open-feign-demo模块                   //Spring Cloud Open Feign集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-ribbon-demo模块                       //Spring Cloud Ribbon集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-security-oauth2-demo模块              //Spring Cloud Security Oauth2集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-security-oauth2-sso-client-demo模块   //Spring Cloud Security Oauth2集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-skywalking-demo模块                   //Spring Cloud Skywalking集成(已实现并有博文总结)
│     └── 模块名称:spring-cloud-stream-demo模块                       //Spring Cloud Stream集成(已实现并有博文总结)
│     └── 模块名称:swagger-demo模块                                   //springfox-swagger2集成(已实现并有博文总结)
│     └── 模块名称:xxl-job模块                                        //xxl-job集成(已实现并有博文总结)
│     └── 模块名称:apache-spark-demo模块                              //Apache Spark集成
│     └── 模块名称:etl-hdfs-hive-hbase-demo模块                       //ETL、HDFS、Hive、Hbase集成
│     └── 模块名称:ddd-mode-demo模块                                  //DDD领域设计
│     └── 模块名称:netty-demo模块                                     //Netty集成
│     └── 模块名称:vue-demo模块                                       //前端vue集成
├── document                                                        // 文档
│     └── JavaKnowledgeDocument                                     //java知识点
│           └── java基础知识点.md                     
│           └── mq知识点.md
│           └── mysql知识点.md
│           └── redis知识点.md
│           └── springcould知识点.md
│           └── spring知识点.md
│     └── FounderDocument                                           //创始人
│           └── 创始人.md

系列文章:快速集成各种微服务相关的技术,帮助大家可以快速集成到自己的项目中,节约开发时间。
提示:系列文章还未全部完成,后续的文章,会慢慢补充进去的。

文章目录

下载包

APM为v8.9.1
Agents为v8.10.0
如下图(示例):
百度云盘分享:
链接:https://pan.baidu.com/s/16zpZHcKqSoui3HUiUrqGnQ?pwd=2022
提取码:2022

配置

数据库使用默认的H2数据库,我使用默认配置,暂时不作修改
application.yml的storage可以选择数据库
如下图(示例):
如果需要修改访问端口可以在这里修改
如下图(示例):
webapp的webapp.yml修改server.port即可,我这里还是用的默认的

启动运行

运行前需要保证电脑配置了JAVA_HOME
如下图(示例):

双击文件直接运行
如下图(示例):
访问http://127.0.0.1:8080
如下图(示例):

idea配置运行skywalking的程序配置jvm参数

如下图(示例):
①配置VM options(skywalking-agent.jar所在位置):-javaagent:E:/skywalking/skywalking-agent/skywalking-agent.jar
注意事项:由于Skywalking 默认是不支持 Spring Cloud Gateway ,若为Cloud服务,需要将optional-plugins目录中最新的apm-spring-cloud-gateway*放入plugins目录中
②配置 Program arguments(Your_ApplicationName为当前的服务名称):-Dskywalking.agent.service_name=Your_ApplicationName
③配置指向写入链路数据的服务器地址-Dskywalking.collector.backend_service=localhost:11800

文章目录

创建spring-cloud-skywalking-demo项目

项目代码:https://gitee.com/java_wxid/java_wxid/tree/master/demo/spring-cloud-skywalking-demo
项目结构如下(示例):

修改pom.xml

代码如下(示例):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-cloud-skywalking-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-skywalking-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--        lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.17</version>
        </dependency>

        <!-- mybatis自动配置依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- SkyWalking 工具类 -->
        <dependency>
            <groupId>org.apache.skywalking</groupId>
            <artifactId>apm-toolkit-trace</artifactId>
            <version>8.10.0</version>
        </dependency>

        <!-- apm-toolkit-logback-1.x -->
        <dependency>
            <groupId>org.apache.skywalking</groupId>
            <artifactId>apm-toolkit-logback-1.x</artifactId>
            <version>8.10.0</version>
        </dependency>




        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

创建logback-spring.xml

代码如下(示例):

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true"  debug="false">

    <springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue=""/>
    <!--日志存放路径-->
    <property name="PATH" value="logs"/>

    <property name="FILE_NAME" value="$spring.application.name"/>

    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.TraceIdPatternLogbackLayout">
                <Pattern>
                    %black(%dISO8601) [%tid] %highlight($LOG_LEVEL_PATTERN:-%5p) [%blue(%t)] %yellow(%C1.): %msg%n%throwable
                </Pattern>
            </layout>
        </encoder>
    </appender>
    <!--trace-->
    <appender name="TRACE_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>$PATH/$FILE_NAME_trace.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>$PATH/$FILE_NAME_trace.%dyyyy-MM-dd.log</FileNamePattern>
            <maxHistory>60</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>[%dyyyy-MM-dd HH:mm:ss.SSS] %highlight([%-5level]) %green([%15.15thread]) %cyan([%logger:%line])--%mdcclient %msg%n</pattern>
        </encoder>
    </appender>

    <!--error-->
    <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>$PATH/$FILE_NAME_error.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>$PATH/$FILE_NAME_error.%dyyyy-MM-dd.log</FileNamePattern>
            <maxHistory>60</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>[%dyyyy-MM-dd HH:mm:ss.SSS] %highlight([%-5level]) %green([%15.15thread]) %cyan([%logger:%line])--%mdcclient %msg%n</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
    </appender>

    <root level="info">
        <appender-ref ref="Console" />
        <appender-ref ref="TRACE_FILE" />
        <appender-ref ref="ERROR_FILE" />
    </root>

</configuration>

创建application.yml

代码如下(示例):

server:
  port: 8199

spring:
  application:
    name: springboot-skywalking-demo
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://139.224.137.74:3306/syncdemo?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
    username: root
    password: ca0a997ee4770063


修改SpringCloudSkywalkingDemoApplication

代码如下(示例):

package com.example.springcloudskywalkingdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;

@MapperScan("com.example.springcloudskywalkingdemo.dao")
@SpringBootApplication
public class SpringCloudSkywalkingDemoApplication 

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



创建IndexController

代码如下(示例):

package com.example.springcloudskywalkingdemo.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@RestController
public class IndexController 

    @RequestMapping("/")
    public String hello()
        return "hello fox";
    

    @RequestMapping("/notify")
    public String notify(@RequestBody Object obj)
        //TODO 告警信息,给技术负责人发短信,钉钉消息,邮件,微信通知等
        System.err.println(obj.toString());
        return "notify successfully";
    


创建ProfileController

代码如下(示例):

package com.example.springcloudskywalkingdemo.controller;


import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@RestController
public class ProfileController 

    @RequestMapping("/profile")
    public String profile()
        process();
        return "success";
    

    @Trace
    private void process()
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        CountDownLatch countDownLatch = new CountDownLatch(2);
        executorService.submit(new Runnable() 
            @Override
            public void run() 
                countDownLatch.countDown();
            
        );
        executorService.submit(new Runnable() 
            @Override
            public void run() 
               // countDownLatch.countDown();
            
        );
        try 
            countDownLatch.await(500, TimeUnit.MILLISECONDS);
         catch (InterruptedException e) 
            e.printStackTrace();
        

    


创建UserController

代码如下(示例):

package com.example.springcloudskywalkingdemo.controller;

import com.example.springcloudskywalkingdemo.entity.User;
import com.example.springcloudskywalkingdemo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.Optional;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController 

    @Autowired
    private UserService userService;

    @RequestMapping("/info/id")
    public User info(@PathVariable("id") Integer id)

        if(id==4)
            throw new IllegalArgumentException("参数异常");
        

        try 
            Thread.sleep(2000);
         catch (InterruptedException e) 
            e.printStackTrace();
        

        return userService.getById(id);
    

    @RequestMapping("/list")
    public List<User> list()
        //TraceContext可以绑定key-value
        TraceContext.putCorrelation("name", "liaozhiwei");
        Optional<String> op = TraceContext.getCorrelation("name");
        log.info("name =  ", op.get());
        //获取跟踪的traceId
        String traceId = TraceContext.traceId();
        log.info("traceId =  ", traceId);
        return userService.list();
    
    
    
    


创建UserMapper

代码如下(示例):

package com.example.springcloudskywalkingdemo.dao;

import com.example.springcloudskywalkingdemo.entity.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@Repository
public interface UserMapper 
    @Select("select * from user")
    List<User> list();

    @Select("select * from user where id=#id")
    User getById(Integer id);

创建User

代码如下(示例):

package com.example.springcloudskywalkingdemo.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User 

    private Integer id;
    private String name;




创建UserService

代码如下(示例):

package com.example.springcloudskywalkingdemo.service;

import com.example.springcloudskywalkingdemo.entity.User;
import java.util.List;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
public interface UserService 

    List<User> list();

    User getById(Integer id);


创建UserServiceImpl

代码如下(示例):

package com.example.springcloudskywalkingdemo.service.impl;

import com.example.springcloudskywalkingdemo.dao.UserMapper;
import com.example.springcloudskywalkingdemo.entity.User;
import com.example.springcloudskywalkingdemo.service.UserService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author zhiwei Liao
 * @Description
 * @Date create in 2022/9/12 0012 21:03
 */
@Service
public class UserServiceImpl implements UserService 
    @Autowired
    private UserMapper userMapper;

    @Trace
    @Tag(key = "list", value = "returnedObj")
    @Override
    public List<User> list()
        return userMapper.list();
    

    @Trace
    @Tags(@Tag(key = "param", value = "arg[0]"),
            @Tag(key = "user", value = "returnedObj"))
    @Override
    public User getById(Integer id)
        return userMapper.getById(id);
    


验证Spring Cloud Skywalking是否工作

调用接口
如下图(示例):
TID查询的追踪ID
如下图(示例):
调用链路显示
如下图(示例):

以上是关于Spring Cloud Skywalking集成的主要内容,如果未能解决你的问题,请参考以下文章

Kubernetes + Spring Cloud 集成链路追踪 SkyWalking

Spring Cloud Skywalking集成

从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(十四) spring boot/cloud +logback/log4j2 集成skywalking日志完整配置

SpringCloud - Spring Cloud Alibaba 之 SkyWalking 分布式链路跟踪;跨多服务追踪,集成日志(十五)

Spring Cloud Alibaba全家桶——微服务链路追踪SkyWalking

Spring Cloud 整合 SkyWalking