简体中文 繁體中文 English Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français Japanese

站内搜索

搜索

活动公告

通知:为庆祝网站一周年,将在5.1日与5.2日开放注册,具体信息请见后续详细公告
04-22 00:04
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

Highcharts与Spring Boot完美融合打造动态数据可视化解决方案 从零开始学习如何在Java Web应用中集成强大图表功能实现数据驱动决策

SunJu_FaceMall

3万

主题

1158

科技点

3万

积分

白金月票

碾压王

积分
32796

立华奏

发表于 2025-8-24 14:30:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在当今数据驱动的时代,数据可视化已成为企业决策过程中不可或缺的一环。通过直观的图表展示,复杂的数据集变得易于理解,帮助决策者快速识别趋势、模式和异常。Highcharts作为一款功能强大的JavaScript图表库,与Spring Boot这一流行的Java框架相结合,可以创建出既美观又实用的数据可视化解决方案。本文将详细介绍如何从零开始,将Highcharts与Spring Boot完美融合,打造动态数据可视化系统。

1. Highcharts与Spring Boot概述

1.1 Highcharts简介

Highcharts是一个基于纯JavaScript的图表库,支持多种图表类型,包括线图、柱状图、饼图、散点图等。它具有以下特点:

• 兼容性好:支持所有现代浏览器,包括移动端浏览器
• 图表类型丰富:提供超过20种图表类型
• 高度可定制:支持自定义图表的各个方面
• 动态更新:支持实时数据更新
• 导出功能:支持将图表导出为图片、PDF等格式

1.2 Spring Boot简介

Spring Boot是Spring框架的一个子项目,旨在简化Spring应用的创建和开发过程。它具有以下特点:

• 自动配置:根据依赖自动配置Spring应用
• 内嵌服务器:如Tomcat、Jetty等,无需部署WAR文件
• 生产就绪:提供监控、健康检查等生产环境所需功能
• 无代码生成:无需生成代码,无需XML配置

1.3 为什么选择Highcharts与Spring Boot结合

将Highcharts与Spring Boot结合有以下优势:

• 前后端分离:Spring Boot提供RESTful API,Highcharts负责前端展示
• 高效开发:Spring Boot简化后端开发,Highcharts简化图表创建
• 实时数据:Spring Boot可以轻松实现数据推送,Highcharts支持实时更新
• 生态系统:两者都有庞大的社区和丰富的文档资源

2. 环境搭建与项目初始化

2.1 开发环境准备

在开始之前,确保以下开发环境已准备就绪:

• JDK 8或更高版本
• Maven 3.6或更高版本
• IDE(如IntelliJ IDEA或Eclipse)
• 现代浏览器(如Chrome、Firefox等)

2.2 创建Spring Boot项目

可以通过Spring Initializr(https://start.spring.io/)快速创建SpringBoot项目,或使用IDE的Spring项目创建功能。

以下是使用Maven创建Spring Boot项目的pom.xml文件基本配置:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <parent>
  6.         <groupId>org.springframework.boot</groupId>
  7.         <artifactId>spring-boot-starter-parent</artifactId>
  8.         <version>2.7.5</version>
  9.         <relativePath/> <!-- lookup parent from repository -->
  10.     </parent>
  11.     <groupId>com.example</groupId>
  12.     <artifactId>highcharts-spring-boot-demo</artifactId>
  13.     <version>0.0.1-SNAPSHOT</version>
  14.     <name>highcharts-spring-boot-demo</name>
  15.     <description>Demo project for Spring Boot with Highcharts</description>
  16.    
  17.     <properties>
  18.         <java.version>11</java.version>
  19.     </properties>
  20.    
  21.     <dependencies>
  22.         <!-- Spring Boot Web -->
  23.         <dependency>
  24.             <groupId>org.springframework.boot</groupId>
  25.             <artifactId>spring-boot-starter-web</artifactId>
  26.         </dependency>
  27.         
  28.         <!-- Spring Boot Data JPA -->
  29.         <dependency>
  30.             <groupId>org.springframework.boot</groupId>
  31.             <artifactId>spring-boot-starter-data-jpa</artifactId>
  32.         </dependency>
  33.         
  34.         <!-- H2 Database -->
  35.         <dependency>
  36.             <groupId>com.h2database</groupId>
  37.             <artifactId>h2</artifactId>
  38.             <scope>runtime</scope>
  39.         </dependency>
  40.         
  41.         <!-- Lombok -->
  42.         <dependency>
  43.             <groupId>org.projectlombok</groupId>
  44.             <artifactId>lombok</artifactId>
  45.             <optional>true</optional>
  46.         </dependency>
  47.         
  48.         <!-- Spring Boot Test -->
  49.         <dependency>
  50.             <groupId>org.springframework.boot</groupId>
  51.             <artifactId>spring-boot-starter-test</artifactId>
  52.             <scope>test</scope>
  53.         </dependency>
  54.     </dependencies>
  55.    
  56.     <build>
  57.         <plugins>
  58.             <plugin>
  59.                 <groupId>org.springframework.boot</groupId>
  60.                 <artifactId>spring-boot-maven-plugin</artifactId>
  61.                 <configuration>
  62.                     <excludes>
  63.                         <exclude>
  64.                             <groupId>org.projectlombok</groupId>
  65.                             <artifactId>lombok</artifactId>
  66.                         </exclude>
  67.                     </excludes>
  68.                 </configuration>
  69.             </plugin>
  70.         </plugins>
  71.     </build>
  72. </project>
复制代码

2.3 项目结构

创建一个标准的Maven项目结构,如下所示:
  1. highcharts-spring-boot-demo/
  2. ├── src/
  3. │   ├── main/
  4. │   │   ├── java/
  5. │   │   │   └── com/
  6. │   │   │       └── example/
  7. │   │   │           └── highchartsspringbootdemo/
  8. │   │   │               ├── controller/
  9. │   │   │               ├── model/
  10. │   │   │               ├── repository/
  11. │   │   │               ├── service/
  12. │   │   │               └── HighchartsSpringBootDemoApplication.java
  13. │   │   └── resources/
  14. │   │       ├── static/
  15. │   │       │   ├── css/
  16. │   │       │   ├── js/
  17. │   │       │   └── index.html
  18. │   │       ├── templates/
  19. │   │       └── application.properties
  20. │   └── test/
  21. │       └── java/
  22. │           └── com/
  23. │               └── example/
  24. │                   └── highchartsspringbootdemo/
  25. └── pom.xml
复制代码

2.4 配置application.properties

在src/main/resources/application.properties文件中添加基本配置:
  1. # Server Configuration
  2. server.port=8080
  3. # H2 Database Configuration
  4. spring.h2.console.enabled=true
  5. spring.h2.console.path=/h2-console
  6. spring.datasource.url=jdbc:h2:mem:testdb
  7. spring.datasource.driverClassName=org.h2.Driver
  8. spring.datasource.username=sa
  9. spring.datasource.password=password
  10. # JPA Configuration
  11. spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
  12. spring.jpa.hibernate.ddl-auto=update
  13. spring.jpa.show-sql=true
复制代码

3. 后端实现(Spring Boot部分)

3.1 创建数据模型

首先,我们需要创建一个数据模型来表示我们的业务数据。假设我们要展示销售数据,可以创建一个SalesData类:
  1. package com.example.highchartsspringbootdemo.model;
  2. import lombok.Data;
  3. import javax.persistence.*;
  4. import java.time.LocalDate;
  5. @Data
  6. @Entity
  7. @Table(name = "sales_data")
  8. public class SalesData {
  9.     @Id
  10.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  11.     private Long id;
  12.    
  13.     @Column(nullable = false)
  14.     private LocalDate date;
  15.    
  16.     @Column(nullable = false)
  17.     private Double amount;
  18.    
  19.     @Column(nullable = false)
  20.     private String product;
  21.    
  22.     @Column(nullable = false)
  23.     private String region;
  24.    
  25.     public SalesData() {
  26.     }
  27.    
  28.     public SalesData(LocalDate date, Double amount, String product, String region) {
  29.         this.date = date;
  30.         this.amount = amount;
  31.         this.product = product;
  32.         this.region = region;
  33.     }
  34. }
复制代码

3.2 创建数据仓库

接下来,创建一个Spring Data JPA仓库接口来处理数据访问:
  1. package com.example.highchartsspringbootdemo.repository;
  2. import com.example.highchartsspringbootdemo.model.SalesData;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.Query;
  5. import org.springframework.stereotype.Repository;
  6. import java.time.LocalDate;
  7. import java.util.List;
  8. @Repository
  9. public interface SalesDataRepository extends JpaRepository<SalesData, Long> {
  10.    
  11.     // 查找指定日期范围内的销售数据
  12.     List<SalesData> findByDateBetween(LocalDate startDate, LocalDate endDate);
  13.    
  14.     // 按产品分组查询销售总额
  15.     @Query("SELECT new com.example.highchartsspringbootdemo.model.ProductSalesSum(s.product, SUM(s.amount)) " +
  16.            "FROM SalesData s WHERE s.date BETWEEN :startDate AND :endDate GROUP BY s.product")
  17.     List<ProductSalesSum> sumSalesByProductBetweenDates(LocalDate startDate, LocalDate endDate);
  18.    
  19.     // 按地区分组查询销售总额
  20.     @Query("SELECT new com.example.highchartsspringbootdemo.model.RegionSalesSum(s.region, SUM(s.amount)) " +
  21.            "FROM SalesData s WHERE s.date BETWEEN :startDate AND :endDate GROUP BY s.region")
  22.     List<RegionSalesSum> sumSalesByRegionBetweenDates(LocalDate startDate, LocalDate endDate);
  23. }
复制代码

为了支持上述查询中的自定义返回类型,我们需要创建两个简单的类:
  1. package com.example.highchartsspringbootdemo.model;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. @Data
  6. @NoArgsConstructor
  7. @AllArgsConstructor
  8. public class ProductSalesSum {
  9.     private String product;
  10.     private Double totalAmount;
  11. }
  12. package com.example.highchartsspringbootdemo.model;
  13. import lombok.AllArgsConstructor;
  14. import lombok.Data;
  15. import lombok.NoArgsConstructor;
  16. @Data
  17. @NoArgsConstructor
  18. @AllArgsConstructor
  19. public class RegionSalesSum {
  20.     private String region;
  21.     private Double totalAmount;
  22. }
复制代码

3.3 创建服务层

创建一个服务类来处理业务逻辑:
  1. package com.example.highchartsspringbootdemo.service;
  2. import com.example.highchartsspringbootdemo.model.ProductSalesSum;
  3. import com.example.highchartsspringbootdemo.model.RegionSalesSum;
  4. import com.example.highchartsspringbootdemo.model.SalesData;
  5. import com.example.highchartsspringbootdemo.repository.SalesDataRepository;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import java.time.LocalDate;
  9. import java.util.List;
  10. import java.util.Random;
  11. @Service
  12. public class SalesDataService {
  13.    
  14.     private final SalesDataRepository salesDataRepository;
  15.    
  16.     @Autowired
  17.     public SalesDataService(SalesDataRepository salesDataRepository) {
  18.         this.salesDataRepository = salesDataRepository;
  19.     }
  20.    
  21.     // 获取所有销售数据
  22.     public List<SalesData> getAllSalesData() {
  23.         return salesDataRepository.findAll();
  24.     }
  25.    
  26.     // 获取指定日期范围内的销售数据
  27.     public List<SalesData> getSalesDataBetweenDates(LocalDate startDate, LocalDate endDate) {
  28.         return salesDataRepository.findByDateBetween(startDate, endDate);
  29.     }
  30.    
  31.     // 按产品获取销售总额
  32.     public List<ProductSalesSum> getSalesSumByProduct(LocalDate startDate, LocalDate endDate) {
  33.         return salesDataRepository.sumSalesByProductBetweenDates(startDate, endDate);
  34.     }
  35.    
  36.     // 按地区获取销售总额
  37.     public List<RegionSalesSum> getSalesSumByRegion(LocalDate startDate, LocalDate endDate) {
  38.         return salesDataRepository.sumSalesByRegionBetweenDates(startDate, endDate);
  39.     }
  40.    
  41.     // 生成模拟数据
  42.     public void generateSampleData() {
  43.         String[] products = {"Laptop", "Smartphone", "Tablet", "Monitor", "Keyboard"};
  44.         String[] regions = {"North", "South", "East", "West", "Central"};
  45.         Random random = new Random();
  46.         
  47.         // 生成过去30天的数据
  48.         for (int i = 0; i < 30; i++) {
  49.             LocalDate date = LocalDate.now().minusDays(i);
  50.             
  51.             // 每天生成5-10条销售记录
  52.             int recordsPerDay = 5 + random.nextInt(6);
  53.             for (int j = 0; j < recordsPerDay; j++) {
  54.                 String product = products[random.nextInt(products.length)];
  55.                 String region = regions[random.nextInt(regions.length)];
  56.                 double amount = 100 + random.nextDouble() * 1000; // 100-1100之间的金额
  57.                
  58.                 SalesData salesData = new SalesData(date, amount, product, region);
  59.                 salesDataRepository.save(salesData);
  60.             }
  61.         }
  62.     }
  63. }
复制代码

3.4 创建控制器

创建一个REST控制器来处理HTTP请求:
  1. package com.example.highchartsspringbootdemo.controller;
  2. import com.example.highchartsspringbootdemo.model.ProductSalesSum;
  3. import com.example.highchartsspringbootdemo.model.RegionSalesSum;
  4. import com.example.highchartsspringbootdemo.model.SalesData;
  5. import com.example.highchartsspringbootdemo.service.SalesDataService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.format.annotation.DateTimeFormat;
  8. import org.springframework.http.ResponseEntity;
  9. import org.springframework.web.bind.annotation.*;
  10. import java.time.LocalDate;
  11. import java.util.List;
  12. @RestController
  13. @RequestMapping("/api/sales")
  14. @CrossOrigin(origins = "*") // 允许跨域请求
  15. public class SalesDataController {
  16.    
  17.     private final SalesDataService salesDataService;
  18.    
  19.     @Autowired
  20.     public SalesDataController(SalesDataService salesDataService) {
  21.         this.salesDataService = salesDataService;
  22.     }
  23.    
  24.     // 获取所有销售数据
  25.     @GetMapping("/all")
  26.     public ResponseEntity<List<SalesData>> getAllSalesData() {
  27.         List<SalesData> salesData = salesDataService.getAllSalesData();
  28.         return ResponseEntity.ok(salesData);
  29.     }
  30.    
  31.     // 获取指定日期范围内的销售数据
  32.     @GetMapping("/range")
  33.     public ResponseEntity<List<SalesData>> getSalesDataBetweenDates(
  34.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
  35.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
  36.         List<SalesData> salesData = salesDataService.getSalesDataBetweenDates(startDate, endDate);
  37.         return ResponseEntity.ok(salesData);
  38.     }
  39.    
  40.     // 按产品获取销售总额
  41.     @GetMapping("/by-product")
  42.     public ResponseEntity<List<ProductSalesSum>> getSalesSumByProduct(
  43.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
  44.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
  45.         List<ProductSalesSum> productSalesSums = salesDataService.getSalesSumByProduct(startDate, endDate);
  46.         return ResponseEntity.ok(productSalesSums);
  47.     }
  48.    
  49.     // 按地区获取销售总额
  50.     @GetMapping("/by-region")
  51.     public ResponseEntity<List<RegionSalesSum>> getSalesSumByRegion(
  52.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
  53.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
  54.         List<RegionSalesSum> regionSalesSums = salesDataService.getSalesSumByRegion(startDate, endDate);
  55.         return ResponseEntity.ok(regionSalesSums);
  56.     }
  57.    
  58.     // 生成模拟数据
  59.     @PostMapping("/generate-sample-data")
  60.     public ResponseEntity<String> generateSampleData() {
  61.         salesDataService.generateSampleData();
  62.         return ResponseEntity.ok("Sample data generated successfully");
  63.     }
  64. }
复制代码

3.5 初始化数据

创建一个数据初始化类,在应用启动时生成一些模拟数据:
  1. package com.example.highchartsspringbootdemo;
  2. import com.example.highchartsspringbootdemo.service.SalesDataService;
  3. import org.springframework.boot.CommandLineRunner;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class DataInitializer implements CommandLineRunner {
  7.    
  8.     private final SalesDataService salesDataService;
  9.    
  10.     public DataInitializer(SalesDataService salesDataService) {
  11.         this.salesDataService = salesDataService;
  12.     }
  13.    
  14.     @Override
  15.     public void run(String... args) throws Exception {
  16.         // 检查数据库是否为空,如果为空则生成模拟数据
  17.         if (salesDataService.getAllSalesData().isEmpty()) {
  18.             salesDataService.generateSampleData();
  19.             System.out.println("Sample data has been generated.");
  20.         }
  21.     }
  22. }
复制代码

4. 前端实现(Highcharts集成)

4.1 创建HTML页面

在src/main/resources/static目录下创建index.html文件:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Sales Data Visualization</title>
  7.    
  8.     <!-- Bootstrap CSS -->
  9.     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  10.    
  11.     <!-- Highcharts CSS -->
  12.     <link rel="stylesheet" href="https://code.highcharts.com/css/highcharts.css">
  13.    
  14.     <!-- Custom CSS -->
  15.     <link rel="stylesheet" href="/css/style.css">
  16. </head>
  17. <body>
  18.     <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  19.         <div class="container">
  20.             <a class="navbar-brand" href="#">Sales Dashboard</a>
  21.             <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
  22.                 <span class="navbar-toggler-icon"></span>
  23.             </button>
  24.             <div class="collapse navbar-collapse" id="navbarNav">
  25.                 <ul class="navbar-nav">
  26.                     <li class="nav-item">
  27.                         <a class="nav-link active" href="#" id="daily-sales-tab">Daily Sales</a>
  28.                     </li>
  29.                     <li class="nav-item">
  30.                         <a class="nav-link" href="#" id="product-sales-tab">Sales by Product</a>
  31.                     </li>
  32.                     <li class="nav-item">
  33.                         <a class="nav-link" href="#" id="region-sales-tab">Sales by Region</a>
  34.                     </li>
  35.                 </ul>
  36.             </div>
  37.         </div>
  38.     </nav>
  39.     <div class="container mt-4">
  40.         <div class="row mb-4">
  41.             <div class="col-md-12">
  42.                 <div class="card">
  43.                     <div class="card-header">
  44.                         <h5 class="card-title">Date Range Selection</h5>
  45.                     </div>
  46.                     <div class="card-body">
  47.                         <div class="row">
  48.                             <div class="col-md-4">
  49.                                 <label for="start-date" class="form-label">Start Date</label>
  50.                                 <input type="date" class="form-control" id="start-date">
  51.                             </div>
  52.                             <div class="col-md-4">
  53.                                 <label for="end-date" class="form-label">End Date</label>
  54.                                 <input type="date" class="form-control" id="end-date">
  55.                             </div>
  56.                             <div class="col-md-4 d-flex align-items-end">
  57.                                 <button id="update-charts" class="btn btn-primary w-100">Update Charts</button>
  58.                             </div>
  59.                         </div>
  60.                     </div>
  61.                 </div>
  62.             </div>
  63.         </div>
  64.         <div class="row">
  65.             <div class="col-md-12">
  66.                 <div class="card">
  67.                     <div class="card-header">
  68.                         <h5 class="card-title" id="chart-title">Daily Sales Trend</h5>
  69.                     </div>
  70.                     <div class="card-body">
  71.                         <div id="sales-chart" style="height: 400px;"></div>
  72.                     </div>
  73.                 </div>
  74.             </div>
  75.         </div>
  76.     </div>
  77.     <!-- Bootstrap JS -->
  78.     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  79.    
  80.     <!-- Highcharts JS -->
  81.     <script src="https://code.highcharts.com/highcharts.js"></script>
  82.     <script src="https://code.highcharts.com/modules/exporting.js"></script>
  83.     <script src="https://code.highcharts.com/modules/export-data.js"></script>
  84.    
  85.     <!-- Custom JS -->
  86.     <script src="/js/app.js"></script>
  87. </body>
  88. </html>
复制代码

4.2 创建CSS文件

在src/main/resources/static/css目录下创建style.css文件:
  1. body {
  2.     background-color: #f8f9fa;
  3.     font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  4. }
  5. .navbar-brand {
  6.     font-weight: bold;
  7. }
  8. .card {
  9.     border: none;
  10.     border-radius: 10px;
  11.     box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  12.     margin-bottom: 1.5rem;
  13. }
  14. .card-header {
  15.     background-color: #fff;
  16.     border-bottom: 1px solid rgba(0, 0, 0, 0.125);
  17.     border-radius: 10px 10px 0 0 !important;
  18. }
  19. .card-title {
  20.     margin-bottom: 0;
  21.     color: #495057;
  22.     font-weight: 600;
  23. }
  24. .btn-primary {
  25.     background-color: #0d6efd;
  26.     border-color: #0d6efd;
  27. }
  28. .btn-primary:hover {
  29.     background-color: #0b5ed7;
  30.     border-color: #0a58ca;
  31. }
  32. .nav-link.active {
  33.     color: #fff !important;
  34.     background-color: #0d6efd;
  35.     border-radius: 0.25rem;
  36. }
  37. .highcharts-container {
  38.     width: 100%;
  39.     height: 100%;
  40. }
  41. .highcharts-title {
  42.     font-weight: 600 !important;
  43. }
  44. .highcharts-axis-title {
  45.     font-weight: 500 !important;
  46. }
  47. .highcharts-legend-item {
  48.     font-weight: 500 !important;
  49. }
复制代码

4.3 创建JavaScript文件

在src/main/resources/static/js目录下创建app.js文件:
  1. document.addEventListener('DOMContentLoaded', function() {
  2.     // 设置默认日期范围(过去30天)
  3.     const endDate = new Date();
  4.     const startDate = new Date();
  5.     startDate.setDate(endDate.getDate() - 30);
  6.    
  7.     // 格式化日期为YYYY-MM-DD
  8.     function formatDate(date) {
  9.         const year = date.getFullYear();
  10.         const month = String(date.getMonth() + 1).padStart(2, '0');
  11.         const day = String(date.getDate()).padStart(2, '0');
  12.         return `${year}-${month}-${day}`;
  13.     }
  14.    
  15.     // 设置日期输入框的默认值
  16.     document.getElementById('start-date').value = formatDate(startDate);
  17.     document.getElementById('end-date').value = formatDate(endDate);
  18.    
  19.     // 当前图表类型
  20.     let currentChartType = 'daily-sales';
  21.    
  22.     // 初始化图表
  23.     let salesChart = Highcharts.chart('sales-chart', {
  24.         chart: {
  25.             type: 'line',
  26.             zoomType: 'x'
  27.         },
  28.         title: {
  29.             text: 'Daily Sales Trend'
  30.         },
  31.         xAxis: {
  32.             type: 'category',
  33.             title: {
  34.                 text: 'Date'
  35.             }
  36.         },
  37.         yAxis: {
  38.             title: {
  39.                 text: 'Sales Amount ($)'
  40.             }
  41.         },
  42.         legend: {
  43.             enabled: true
  44.         },
  45.         plotOptions: {
  46.             line: {
  47.                 dataLabels: {
  48.                     enabled: false
  49.                 },
  50.                 enableMouseTracking: true
  51.             }
  52.         },
  53.         series: []
  54.     });
  55.    
  56.     // 加载数据的函数
  57.     async function loadData(chartType, startDate, endDate) {
  58.         try {
  59.             let url;
  60.             let chartConfig;
  61.             
  62.             switch (chartType) {
  63.                 case 'daily-sales':
  64.                     url = `/api/sales/range?startDate=${startDate}&endDate=${endDate}`;
  65.                     chartConfig = configureDailySalesChart;
  66.                     break;
  67.                 case 'product-sales':
  68.                     url = `/api/sales/by-product?startDate=${startDate}&endDate=${endDate}`;
  69.                     chartConfig = configureProductSalesChart;
  70.                     break;
  71.                 case 'region-sales':
  72.                     url = `/api/sales/by-region?startDate=${startDate}&endDate=${endDate}`;
  73.                     chartConfig = configureRegionSalesChart;
  74.                     break;
  75.                 default:
  76.                     throw new Error('Unknown chart type');
  77.             }
  78.             
  79.             const response = await fetch(url);
  80.             if (!response.ok) {
  81.                 throw new Error('Network response was not ok');
  82.             }
  83.             
  84.             const data = await response.json();
  85.             chartConfig(data);
  86.         } catch (error) {
  87.             console.error('Error loading data:', error);
  88.             showError('Failed to load data. Please try again later.');
  89.         }
  90.     }
  91.    
  92.     // 配置每日销售图表
  93.     function configureDailySalesChart(data) {
  94.         // 按日期分组数据
  95.         const groupedData = {};
  96.         data.forEach(item => {
  97.             const date = item.date;
  98.             if (!groupedData[date]) {
  99.                 groupedData[date] = 0;
  100.             }
  101.             groupedData[date] += item.amount;
  102.         });
  103.         
  104.         // 转换为Highcharts格式
  105.         const chartData = Object.keys(groupedData).map(date => {
  106.             return [date, groupedData[date]];
  107.         });
  108.         
  109.         // 更新图表
  110.         salesChart.update({
  111.             title: {
  112.                 text: 'Daily Sales Trend'
  113.             },
  114.             xAxis: {
  115.                 type: 'category',
  116.                 title: {
  117.                     text: 'Date'
  118.                 }
  119.             },
  120.             yAxis: {
  121.                 title: {
  122.                     text: 'Sales Amount ($)'
  123.                 }
  124.             },
  125.             series: [{
  126.                 name: 'Daily Sales',
  127.                 data: chartData,
  128.                 color: '#0d6efd'
  129.             }]
  130.         });
  131.     }
  132.    
  133.     // 配置产品销售图表
  134.     function configureProductSalesChart(data) {
  135.         // 转换为Highcharts格式
  136.         const chartData = data.map(item => {
  137.             return [item.product, item.totalAmount];
  138.         });
  139.         
  140.         // 更新图表
  141.         salesChart.update({
  142.             chart: {
  143.                 type: 'column'
  144.             },
  145.             title: {
  146.                 text: 'Sales by Product'
  147.             },
  148.             xAxis: {
  149.                 type: 'category',
  150.                 title: {
  151.                     text: 'Product'
  152.                 }
  153.             },
  154.             yAxis: {
  155.                 title: {
  156.                     text: 'Sales Amount ($)'
  157.                 }
  158.             },
  159.             series: [{
  160.                 name: 'Product Sales',
  161.                 data: chartData,
  162.                 color: '#198754'
  163.             }]
  164.         });
  165.     }
  166.    
  167.     // 配置地区销售图表
  168.     function configureRegionSalesChart(data) {
  169.         // 转换为Highcharts格式
  170.         const chartData = data.map(item => {
  171.             return [item.region, item.totalAmount];
  172.         });
  173.         
  174.         // 更新图表
  175.         salesChart.update({
  176.             chart: {
  177.                 type: 'pie'
  178.             },
  179.             title: {
  180.                 text: 'Sales by Region'
  181.             },
  182.             xAxis: {
  183.                 title: {
  184.                     text: ''
  185.                 }
  186.             },
  187.             yAxis: {
  188.                 title: {
  189.                     text: ''
  190.                 }
  191.             },
  192.             plotOptions: {
  193.                 pie: {
  194.                     allowPointSelect: true,
  195.                     cursor: 'pointer',
  196.                     dataLabels: {
  197.                         enabled: true,
  198.                         format: '<b>{point.name}</b>: ${point.y:.2f}'
  199.                     }
  200.                 }
  201.             },
  202.             series: [{
  203.                 name: 'Region Sales',
  204.                 data: chartData
  205.             }]
  206.         });
  207.     }
  208.    
  209.     // 显示错误信息
  210.     function showError(message) {
  211.         const alertDiv = document.createElement('div');
  212.         alertDiv.className = 'alert alert-danger alert-dismissible fade show';
  213.         alertDiv.innerHTML = `
  214.             ${message}
  215.             <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  216.         `;
  217.         
  218.         const container = document.querySelector('.container');
  219.         container.insertBefore(alertDiv, container.firstChild);
  220.         
  221.         // 3秒后自动关闭
  222.         setTimeout(() => {
  223.             alertDiv.classList.remove('show');
  224.             setTimeout(() => {
  225.                 alertDiv.remove();
  226.             }, 150);
  227.         }, 3000);
  228.     }
  229.    
  230.     // 初始加载数据
  231.     loadData(currentChartType, formatDate(startDate), formatDate(endDate));
  232.    
  233.     // 更新图表按钮点击事件
  234.     document.getElementById('update-charts').addEventListener('click', function() {
  235.         const startDate = document.getElementById('start-date').value;
  236.         const endDate = document.getElementById('end-date').value;
  237.         
  238.         if (!startDate || !endDate) {
  239.             showError('Please select both start and end dates.');
  240.             return;
  241.         }
  242.         
  243.         if (new Date(startDate) > new Date(endDate)) {
  244.             showError('Start date must be before end date.');
  245.             return;
  246.         }
  247.         
  248.         loadData(currentChartType, startDate, endDate);
  249.     });
  250.    
  251.     // 标签页切换事件
  252.     document.getElementById('daily-sales-tab').addEventListener('click', function(e) {
  253.         e.preventDefault();
  254.         currentChartType = 'daily-sales';
  255.         document.querySelectorAll('.nav-link').forEach(link => {
  256.             link.classList.remove('active');
  257.         });
  258.         this.classList.add('active');
  259.         
  260.         const startDate = document.getElementById('start-date').value;
  261.         const endDate = document.getElementById('end-date').value;
  262.         loadData(currentChartType, startDate, endDate);
  263.     });
  264.    
  265.     document.getElementById('product-sales-tab').addEventListener('click', function(e) {
  266.         e.preventDefault();
  267.         currentChartType = 'product-sales';
  268.         document.querySelectorAll('.nav-link').forEach(link => {
  269.             link.classList.remove('active');
  270.         });
  271.         this.classList.add('active');
  272.         
  273.         const startDate = document.getElementById('start-date').value;
  274.         const endDate = document.getElementById('end-date').value;
  275.         loadData(currentChartType, startDate, endDate);
  276.     });
  277.    
  278.     document.getElementById('region-sales-tab').addEventListener('click', function(e) {
  279.         e.preventDefault();
  280.         currentChartType = 'region-sales';
  281.         document.querySelectorAll('.nav-link').forEach(link => {
  282.             link.classList.remove('active');
  283.         });
  284.         this.classList.add('active');
  285.         
  286.         const startDate = document.getElementById('start-date').value;
  287.         const endDate = document.getElementById('end-date').value;
  288.         loadData(currentChartType, startDate, endDate);
  289.     });
  290. });
复制代码

5. 数据交互和动态更新

5.1 实现实时数据更新

为了实现实时数据更新,我们可以使用WebSocket技术。首先,添加WebSocket依赖到pom.xml:
  1. <!-- WebSocket -->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-websocket</artifactId>
  5. </dependency>
复制代码

5.2 配置WebSocket

创建一个WebSocket配置类:
  1. package com.example.highchartsspringbootdemo.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
  4. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  5. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  6. import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
  7. @Configuration
  8. @EnableWebSocketMessageBroker
  9. public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
  10.    
  11.     @Override
  12.     public void configureMessageBroker(MessageBrokerRegistry config) {
  13.         config.enableSimpleBroker("/topic");
  14.         config.setApplicationDestinationPrefixes("/app");
  15.     }
  16.    
  17.     @Override
  18.     public void registerStompEndpoints(StompEndpointRegistry registry) {
  19.         registry.addEndpoint("/ws").withSockJS();
  20.     }
  21. }
复制代码

5.3 创建实时数据控制器

创建一个控制器来处理实时数据推送:
  1. package com.example.highchartsspringbootdemo.controller;
  2. import com.example.highchartsspringbootdemo.model.SalesData;
  3. import com.example.highchartsspringbootdemo.service.SalesDataService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.messaging.handler.annotation.MessageMapping;
  6. import org.springframework.messaging.handler.annotation.SendTo;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import java.time.LocalDate;
  11. import java.util.List;
  12. import java.util.Random;
  13. import java.util.concurrent.Executors;
  14. import java.util.concurrent.ScheduledExecutorService;
  15. import java.util.concurrent.TimeUnit;
  16. @Controller
  17. public class RealTimeDataController {
  18.    
  19.     private final SalesDataService salesDataService;
  20.     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  21.    
  22.     @Autowired
  23.     public RealTimeDataController(SalesDataService salesDataService) {
  24.         this.salesDataService = salesDataService;
  25.         startRealTimeDataGeneration();
  26.     }
  27.    
  28.     // 开始实时生成数据
  29.     private void startRealTimeDataGeneration() {
  30.         scheduler.scheduleAtFixedRate(() -> {
  31.             // 生成新的销售数据
  32.             String[] products = {"Laptop", "Smartphone", "Tablet", "Monitor", "Keyboard"};
  33.             String[] regions = {"North", "South", "East", "West", "Central"};
  34.             Random random = new Random();
  35.             
  36.             String product = products[random.nextInt(products.length)];
  37.             String region = regions[random.nextInt(regions.length)];
  38.             double amount = 100 + random.nextDouble() * 1000;
  39.             
  40.             SalesData newSalesData = new SalesData(LocalDate.now(), amount, product, region);
  41.             salesDataService.save(newSalesData);
  42.             
  43.             // 推送到前端
  44.             broadcastNewSalesData(newSalesData);
  45.         }, 10, 10, TimeUnit.SECONDS); // 每10秒生成一次新数据
  46.     }
  47.    
  48.     // 广播新销售数据
  49.     private void broadcastNewSalesData(SalesData salesData) {
  50.         // 这里可以通过WebSocket将新数据推送到前端
  51.         // 实际实现取决于你的WebSocket配置
  52.     }
  53.    
  54.     // 获取今天的销售数据
  55.     @GetMapping("/api/sales/today")
  56.     @ResponseBody
  57.     public List<SalesData> getTodaySalesData() {
  58.         LocalDate today = LocalDate.now();
  59.         return salesDataService.getSalesDataBetweenDates(today, today);
  60.     }
  61.    
  62.     // 处理WebSocket消息
  63.     @MessageMapping("/hello")
  64.     @SendTo("/topic/greetings")
  65.     public String greeting(String message) throws Exception {
  66.         return "Hello, " + message + "!";
  67.     }
  68. }
复制代码

5.4 更新前端以支持实时数据

在app.js中添加WebSocket支持:
  1. // 在文件顶部添加WebSocket连接
  2. let stompClient = null;
  3. function connect() {
  4.     const socket = new SockJS('/ws');
  5.     stompClient = Stomp.over(socket);
  6.     stompClient.connect({}, function(frame) {
  7.         console.log('Connected: ' + frame);
  8.         stompClient.subscribe('/topic/sales', function(message) {
  9.             const salesData = JSON.parse(message.body);
  10.             updateChartWithNewData(salesData);
  11.         });
  12.     }, function(error) {
  13.         console.log('Error: ' + error);
  14.         // 5秒后尝试重新连接
  15.         setTimeout(connect, 5000);
  16.     });
  17. }
  18. // 断开连接
  19. function disconnect() {
  20.     if (stompClient !== null) {
  21.         stompClient.disconnect();
  22.     }
  23.     console.log("Disconnected");
  24. }
  25. // 更新图表数据
  26. function updateChartWithNewData(newData) {
  27.     // 根据当前图表类型更新数据
  28.     if (currentChartType === 'daily-sales') {
  29.         // 检查是否已有该日期的数据点
  30.         const date = newData.date;
  31.         let found = false;
  32.         
  33.         salesChart.series[0].points.forEach(point => {
  34.             if (point.category === date) {
  35.                 point.update(point.y + newData.amount);
  36.                 found = true;
  37.             }
  38.         });
  39.         
  40.         // 如果没有找到该日期的数据点,添加新的
  41.         if (!found) {
  42.             salesChart.series[0].addPoint([date, newData.amount]);
  43.         }
  44.     } else if (currentChartType === 'product-sales') {
  45.         // 查找并更新产品数据
  46.         const product = newData.product;
  47.         let found = false;
  48.         
  49.         salesChart.series[0].points.forEach(point => {
  50.             if (point.category === product) {
  51.                 point.update(point.y + newData.amount);
  52.                 found = true;
  53.             }
  54.         });
  55.         
  56.         // 如果没有找到该产品的数据点,添加新的
  57.         if (!found) {
  58.             // 重新加载整个图表数据
  59.             const startDate = document.getElementById('start-date').value;
  60.             const endDate = document.getElementById('end-date').value;
  61.             loadData(currentChartType, startDate, endDate);
  62.         }
  63.     } else if (currentChartType === 'region-sales') {
  64.         // 重新加载整个图表数据
  65.         const startDate = document.getElementById('start-date').value;
  66.         const endDate = document.getElementById('end-date').value;
  67.         loadData(currentChartType, startDate, endDate);
  68.     }
  69. }
  70. // 在页面加载时连接WebSocket
  71. window.addEventListener('load', function() {
  72.     connect();
  73. });
  74. // 在页面关闭时断开连接
  75. window.addEventListener('beforeunload', function() {
  76.     disconnect();
  77. });
复制代码

6. 实际案例和最佳实践

6.1 案例一:销售仪表板

我们已经实现了一个销售仪表板,它可以展示每日销售趋势、按产品分类的销售数据和按地区分类的销售数据。这个仪表板具有以下特点:

• 交互式图表:用户可以与图表交互,如缩放、悬停查看详细数据等
• 日期范围选择:用户可以选择特定日期范围查看数据
• 实时更新:图表可以实时更新以反映新数据
• 响应式设计:仪表板适应不同屏幕尺寸

6.2 案例二:系统性能监控

让我们创建一个系统性能监控的例子,展示如何使用Highcharts和Spring Boot来监控系统性能。

首先,创建一个系统性能数据模型:
  1. package com.example.highchartsspringbootdemo.model;
  2. import lombok.Data;
  3. import javax.persistence.*;
  4. import java.time.LocalDateTime;
  5. @Data
  6. @Entity
  7. @Table(name = "system_performance")
  8. public class SystemPerformance {
  9.     @Id
  10.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  11.     private Long id;
  12.    
  13.     @Column(nullable = false)
  14.     private LocalDateTime timestamp;
  15.    
  16.     @Column(nullable = false)
  17.     private Double cpuUsage;
  18.    
  19.     @Column(nullable = false)
  20.     private Double memoryUsage;
  21.    
  22.     @Column(nullable = false)
  23.     private Double diskUsage;
  24.    
  25.     @Column(nullable = false)
  26.     private Double networkIn;
  27.    
  28.     @Column(nullable = false)
  29.     private Double networkOut;
  30.    
  31.     public SystemPerformance() {
  32.     }
  33.    
  34.     public SystemPerformance(LocalDateTime timestamp, Double cpuUsage, Double memoryUsage,
  35.                             Double diskUsage, Double networkIn, Double networkOut) {
  36.         this.timestamp = timestamp;
  37.         this.cpuUsage = cpuUsage;
  38.         this.memoryUsage = memoryUsage;
  39.         this.diskUsage = diskUsage;
  40.         this.networkIn = networkIn;
  41.         this.networkOut = networkOut;
  42.     }
  43. }
复制代码

然后,创建一个仓库接口:
  1. package com.example.highchartsspringbootdemo.repository;
  2. import com.example.highchartsspringbootdemo.model.SystemPerformance;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.stereotype.Repository;
  5. import java.time.LocalDateTime;
  6. import java.util.List;
  7. @Repository
  8. public interface SystemPerformanceRepository extends JpaRepository<SystemPerformance, Long> {
  9.    
  10.     // 查找指定时间范围内的性能数据
  11.     List<SystemPerformance> findByTimestampBetweenOrderByTimestamp(LocalDateTime startTime, LocalDateTime endTime);
  12. }
复制代码

创建一个服务类:
  1. package com.example.highchartsspringbootdemo.service;
  2. import com.example.highchartsspringbootdemo.model.SystemPerformance;
  3. import com.example.highchartsspringbootdemo.repository.SystemPerformanceRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import java.lang.management.ManagementFactory;
  7. import java.lang.management.OperatingSystemMXBean;
  8. import java.time.LocalDateTime;
  9. import java.util.List;
  10. import java.util.Random;
  11. @Service
  12. public class SystemPerformanceService {
  13.    
  14.     private final SystemPerformanceRepository systemPerformanceRepository;
  15.    
  16.     @Autowired
  17.     public SystemPerformanceService(SystemPerformanceRepository systemPerformanceRepository) {
  18.         this.systemPerformanceRepository = systemPerformanceRepository;
  19.     }
  20.    
  21.     // 获取指定时间范围内的性能数据
  22.     public List<SystemPerformance> getPerformanceDataBetweenTimes(LocalDateTime startTime, LocalDateTime endTime) {
  23.         return systemPerformanceRepository.findByTimestampBetweenOrderByTimestamp(startTime, endTime);
  24.     }
  25.    
  26.     // 保存性能数据
  27.     public SystemPerformance save(SystemPerformance systemPerformance) {
  28.         return systemPerformanceRepository.save(systemPerformance);
  29.     }
  30.    
  31.     // 获取当前系统性能数据
  32.     public SystemPerformance getCurrentSystemPerformance() {
  33.         OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
  34.         com.sun.management.OperatingSystemMXBean sunOsBean =
  35.             (com.sun.management.OperatingSystemMXBean) osBean;
  36.         
  37.         // 获取系统负载
  38.         double cpuUsage = sunOsBean.getSystemCpuLoad() * 100;
  39.         double memoryUsage = (1 - (double) sunOsBean.getFreePhysicalMemorySize() /
  40.                              (double) sunOsBean.getTotalPhysicalMemorySize()) * 100;
  41.         
  42.         // 模拟磁盘和网络使用率
  43.         Random random = new Random();
  44.         double diskUsage = 30 + random.nextDouble() * 50; // 30-80%
  45.         double networkIn = random.nextDouble() * 100; // 0-100 MB/s
  46.         double networkOut = random.nextDouble() * 100; // 0-100 MB/s
  47.         
  48.         return new SystemPerformance(
  49.             LocalDateTime.now(),
  50.             cpuUsage,
  51.             memoryUsage,
  52.             diskUsage,
  53.             networkIn,
  54.             networkOut
  55.         );
  56.     }
  57.    
  58.     // 生成模拟性能数据
  59.     public void generateSamplePerformanceData() {
  60.         Random random = new Random();
  61.         LocalDateTime now = LocalDateTime.now();
  62.         
  63.         // 生成过去24小时的数据,每5分钟一条
  64.         for (int i = 288; i >= 0; i--) { // 24小时 * 12次/小时 = 288次
  65.             LocalDateTime timestamp = now.minusMinutes(i * 5);
  66.             
  67.             double cpuUsage = Math.max(0, Math.min(100, 20 + random.nextDouble() * 60));
  68.             double memoryUsage = Math.max(0, Math.min(100, 30 + random.nextDouble() * 50));
  69.             double diskUsage = Math.max(0, Math.min(100, 20 + random.nextDouble() * 60));
  70.             double networkIn = random.nextDouble() * 100;
  71.             double networkOut = random.nextDouble() * 100;
  72.             
  73.             SystemPerformance performance = new SystemPerformance(
  74.                 timestamp,
  75.                 cpuUsage,
  76.                 memoryUsage,
  77.                 diskUsage,
  78.                 networkIn,
  79.                 networkOut
  80.             );
  81.             
  82.             systemPerformanceRepository.save(performance);
  83.         }
  84.     }
  85. }
复制代码

创建一个控制器:
  1. package com.example.highchartsspringbootdemo.controller;
  2. import com.example.highchartsspringbootdemo.model.SystemPerformance;
  3. import com.example.highchartsspringbootdemo.service.SystemPerformanceService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.format.annotation.DateTimeFormat;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.*;
  8. import java.time.LocalDateTime;
  9. import java.util.List;
  10. @RestController
  11. @RequestMapping("/api/performance")
  12. @CrossOrigin(origins = "*")
  13. public class SystemPerformanceController {
  14.    
  15.     private final SystemPerformanceService systemPerformanceService;
  16.    
  17.     @Autowired
  18.     public SystemPerformanceController(SystemPerformanceService systemPerformanceService) {
  19.         this.systemPerformanceService = systemPerformanceService;
  20.     }
  21.    
  22.     // 获取指定时间范围内的性能数据
  23.     @GetMapping("/range")
  24.     public ResponseEntity<List<SystemPerformance>> getPerformanceDataBetweenTimes(
  25.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
  26.             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
  27.         List<SystemPerformance> performanceData =
  28.             systemPerformanceService.getPerformanceDataBetweenTimes(startTime, endTime);
  29.         return ResponseEntity.ok(performanceData);
  30.     }
  31.    
  32.     // 获取当前系统性能
  33.     @GetMapping("/current")
  34.     public ResponseEntity<SystemPerformance> getCurrentSystemPerformance() {
  35.         SystemPerformance currentPerformance = systemPerformanceService.getCurrentSystemPerformance();
  36.         return ResponseEntity.ok(currentPerformance);
  37.     }
  38.    
  39.     // 生成模拟性能数据
  40.     @PostMapping("/generate-sample-data")
  41.     public ResponseEntity<String> generateSamplePerformanceData() {
  42.         systemPerformanceService.generateSamplePerformanceData();
  43.         return ResponseEntity.ok("Sample performance data generated successfully");
  44.     }
  45. }
复制代码

创建一个性能监控的HTML页面performance.html:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>System Performance Monitor</title>
  7.    
  8.     <!-- Bootstrap CSS -->
  9.     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  10.    
  11.     <!-- Highcharts CSS -->
  12.     <link rel="stylesheet" href="https://code.highcharts.com/css/highcharts.css">
  13.    
  14.     <!-- Custom CSS -->
  15.     <link rel="stylesheet" href="/css/style.css">
  16. </head>
  17. <body>
  18.     <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  19.         <div class="container">
  20.             <a class="navbar-brand" href="#">System Performance Monitor</a>
  21.             <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
  22.                 <span class="navbar-toggler-icon"></span>
  23.             </button>
  24.             <div class="collapse navbar-collapse" id="navbarNav">
  25.                 <ul class="navbar-nav">
  26.                     <li class="nav-item">
  27.                         <a class="nav-link active" href="#" id="overview-tab">Overview</a>
  28.                     </li>
  29.                     <li class="nav-item">
  30.                         <a class="nav-link" href="#" id="cpu-tab">CPU Usage</a>
  31.                     </li>
  32.                     <li class="nav-item">
  33.                         <a class="nav-link" href="#" id="memory-tab">Memory Usage</a>
  34.                     </li>
  35.                     <li class="nav-item">
  36.                         <a class="nav-link" href="#" id="disk-tab">Disk Usage</a>
  37.                     </li>
  38.                     <li class="nav-item">
  39.                         <a class="nav-link" href="#" id="network-tab">Network</a>
  40.                     </li>
  41.                 </ul>
  42.             </div>
  43.         </div>
  44.     </nav>
  45.     <div class="container mt-4">
  46.         <div class="row mb-4">
  47.             <div class="col-md-12">
  48.                 <div class="card">
  49.                     <div class="card-header">
  50.                         <h5 class="card-title">Time Range Selection</h5>
  51.                     </div>
  52.                     <div class="card-body">
  53.                         <div class="row">
  54.                             <div class="col-md-4">
  55.                                 <label for="start-time" class="form-label">Start Time</label>
  56.                                 <input type="datetime-local" class="form-control" id="start-time">
  57.                             </div>
  58.                             <div class="col-md-4">
  59.                                 <label for="end-time" class="form-label">End Time</label>
  60.                                 <input type="datetime-local" class="form-control" id="end-time">
  61.                             </div>
  62.                             <div class="col-md-4 d-flex align-items-end">
  63.                                 <button id="update-charts" class="btn btn-primary w-100">Update Charts</button>
  64.                             </div>
  65.                         </div>
  66.                     </div>
  67.                 </div>
  68.             </div>
  69.         </div>
  70.         <div class="row mb-4">
  71.             <div class="col-md-3">
  72.                 <div class="card text-white bg-primary">
  73.                     <div class="card-body">
  74.                         <h5 class="card-title">CPU Usage</h5>
  75.                         <h2 id="cpu-usage" class="card-text">0%</h2>
  76.                     </div>
  77.                 </div>
  78.             </div>
  79.             <div class="col-md-3">
  80.                 <div class="card text-white bg-success">
  81.                     <div class="card-body">
  82.                         <h5 class="card-title">Memory Usage</h5>
  83.                         <h2 id="memory-usage" class="card-text">0%</h2>
  84.                     </div>
  85.                 </div>
  86.             </div>
  87.             <div class="col-md-3">
  88.                 <div class="card text-white bg-warning">
  89.                     <div class="card-body">
  90.                         <h5 class="card-title">Disk Usage</h5>
  91.                         <h2 id="disk-usage" class="card-text">0%</h2>
  92.                     </div>
  93.                 </div>
  94.             </div>
  95.             <div class="col-md-3">
  96.                 <div class="card text-white bg-info">
  97.                     <div class="card-body">
  98.                         <h5 class="card-title">Network I/O</h5>
  99.                         <h2 id="network-usage" class="card-text">0 MB/s</h2>
  100.                     </div>
  101.                 </div>
  102.             </div>
  103.         </div>
  104.         <div class="row">
  105.             <div class="col-md-12">
  106.                 <div class="card">
  107.                     <div class="card-header">
  108.                         <h5 class="card-title" id="chart-title">System Performance Overview</h5>
  109.                     </div>
  110.                     <div class="card-body">
  111.                         <div id="performance-chart" style="height: 400px;"></div>
  112.                     </div>
  113.                 </div>
  114.             </div>
  115.         </div>
  116.     </div>
  117.     <!-- Bootstrap JS -->
  118.     <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  119.    
  120.     <!-- Highcharts JS -->
  121.     <script src="https://code.highcharts.com/highcharts.js"></script>
  122.     <script src="https://code.highcharts.com/modules/exporting.js"></script>
  123.     <script src="https://code.highcharts.com/modules/export-data.js"></script>
  124.    
  125.     <!-- SockJS and Stomp for WebSocket -->
  126.     <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js"></script>
  127.     <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
  128.    
  129.     <!-- Custom JS -->
  130.     <script src="/js/performance.js"></script>
  131. </body>
  132. </html>
复制代码

创建对应的JavaScript文件performance.js:
  1. document.addEventListener('DOMContentLoaded', function() {
  2.     // 设置默认时间范围(过去24小时)
  3.     const endTime = new Date();
  4.     const startTime = new Date();
  5.     startTime.setHours(endTime.getHours() - 24);
  6.    
  7.     // 格式化日期时间为YYYY-MM-DDTHH:MM格式
  8.     function formatDateTime(date) {
  9.         const year = date.getFullYear();
  10.         const month = String(date.getMonth() + 1).padStart(2, '0');
  11.         const day = String(date.getDate()).padStart(2, '0');
  12.         const hours = String(date.getHours()).padStart(2, '0');
  13.         const minutes = String(date.getMinutes()).padStart(2, '0');
  14.         return `${year}-${month}-${day}T${hours}:${minutes}`;
  15.     }
  16.    
  17.     // 设置时间输入框的默认值
  18.     document.getElementById('start-time').value = formatDateTime(startTime);
  19.     document.getElementById('end-time').value = formatDateTime(endTime);
  20.    
  21.     // 当前图表类型
  22.     let currentChartType = 'overview';
  23.    
  24.     // 初始化图表
  25.     let performanceChart = Highcharts.chart('performance-chart', {
  26.         chart: {
  27.             zoomType: 'x'
  28.         },
  29.         title: {
  30.             text: 'System Performance Overview'
  31.         },
  32.         xAxis: {
  33.             type: 'datetime',
  34.             title: {
  35.                 text: 'Time'
  36.             }
  37.         },
  38.         yAxis: {
  39.             title: {
  40.                 text: 'Usage (%)'
  41.             },
  42.             min: 0,
  43.             max: 100
  44.         },
  45.         legend: {
  46.             enabled: true
  47.         },
  48.         plotOptions: {
  49.             line: {
  50.                 dataLabels: {
  51.                     enabled: false
  52.                 },
  53.                 enableMouseTracking: true
  54.             }
  55.         },
  56.         series: []
  57.     });
  58.    
  59.     // WebSocket连接
  60.     let stompClient = null;
  61.    
  62.     function connect() {
  63.         const socket = new SockJS('/ws');
  64.         stompClient = Stomp.over(socket);
  65.         stompClient.connect({}, function(frame) {
  66.             console.log('Connected: ' + frame);
  67.             stompClient.subscribe('/topic/performance', function(message) {
  68.                 const performanceData = JSON.parse(message.body);
  69.                 updateCurrentMetrics(performanceData);
  70.                 updateChartWithNewData(performanceData);
  71.             });
  72.         }, function(error) {
  73.             console.log('Error: ' + error);
  74.             // 5秒后尝试重新连接
  75.             setTimeout(connect, 5000);
  76.         });
  77.     }
  78.    
  79.     // 断开连接
  80.     function disconnect() {
  81.         if (stompClient !== null) {
  82.             stompClient.disconnect();
  83.         }
  84.         console.log("Disconnected");
  85.     }
  86.    
  87.     // 更新当前指标
  88.     function updateCurrentMetrics(data) {
  89.         document.getElementById('cpu-usage').textContent = data.cpuUsage.toFixed(1) + '%';
  90.         document.getElementById('memory-usage').textContent = data.memoryUsage.toFixed(1) + '%';
  91.         document.getElementById('disk-usage').textContent = data.diskUsage.toFixed(1) + '%';
  92.         document.getElementById('network-usage').textContent =
  93.             (data.networkIn + data.networkOut).toFixed(1) + ' MB/s';
  94.     }
  95.    
  96.     // 加载数据的函数
  97.     async function loadPerformanceData(chartType, startTime, endTime) {
  98.         try {
  99.             const startTimeISO = new Date(startTime).toISOString();
  100.             const endTimeISO = new Date(endTime).toISOString();
  101.             
  102.             const response = await fetch(`/api/performance/range?startTime=${startTimeISO}&endTime=${endTimeISO}`);
  103.             if (!response.ok) {
  104.                 throw new Error('Network response was not ok');
  105.             }
  106.             
  107.             const data = await response.json();
  108.             configureChart(chartType, data);
  109.         } catch (error) {
  110.             console.error('Error loading performance data:', error);
  111.             showError('Failed to load performance data. Please try again later.');
  112.         }
  113.     }
  114.    
  115.     // 配置图表
  116.     function configureChart(chartType, data) {
  117.         // 转换时间戳为Highcharts格式
  118.         const chartData = data.map(item => {
  119.             return [new Date(item.timestamp).getTime(), item];
  120.         });
  121.         
  122.         switch (chartType) {
  123.             case 'overview':
  124.                 performanceChart.update({
  125.                     title: {
  126.                         text: 'System Performance Overview'
  127.                     },
  128.                     yAxis: {
  129.                         title: {
  130.                             text: 'Usage (%)'
  131.                         },
  132.                         min: 0,
  133.                         max: 100
  134.                     },
  135.                     series: [
  136.                         {
  137.                             name: 'CPU Usage',
  138.                             data: chartData.map(item => [item[0], item[1].cpuUsage]),
  139.                             color: '#0d6efd'
  140.                         },
  141.                         {
  142.                             name: 'Memory Usage',
  143.                             data: chartData.map(item => [item[0], item[1].memoryUsage]),
  144.                             color: '#198754'
  145.                         },
  146.                         {
  147.                             name: 'Disk Usage',
  148.                             data: chartData.map(item => [item[0], item[1].diskUsage]),
  149.                             color: '#ffc107'
  150.                         }
  151.                     ]
  152.                 });
  153.                 break;
  154.                
  155.             case 'cpu':
  156.                 performanceChart.update({
  157.                     title: {
  158.                         text: 'CPU Usage'
  159.                     },
  160.                     yAxis: {
  161.                         title: {
  162.                             text: 'Usage (%)'
  163.                         },
  164.                         min: 0,
  165.                         max: 100
  166.                     },
  167.                     series: [
  168.                         {
  169.                             name: 'CPU Usage',
  170.                             data: chartData.map(item => [item[0], item[1].cpuUsage]),
  171.                             color: '#0d6efd'
  172.                         }
  173.                     ]
  174.                 });
  175.                 break;
  176.                
  177.             case 'memory':
  178.                 performanceChart.update({
  179.                     title: {
  180.                         text: 'Memory Usage'
  181.                     },
  182.                     yAxis: {
  183.                         title: {
  184.                             text: 'Usage (%)'
  185.                         },
  186.                         min: 0,
  187.                         max: 100
  188.                     },
  189.                     series: [
  190.                         {
  191.                             name: 'Memory Usage',
  192.                             data: chartData.map(item => [item[0], item[1].memoryUsage]),
  193.                             color: '#198754'
  194.                         }
  195.                     ]
  196.                 });
  197.                 break;
  198.                
  199.             case 'disk':
  200.                 performanceChart.update({
  201.                     title: {
  202.                         text: 'Disk Usage'
  203.                     },
  204.                     yAxis: {
  205.                         title: {
  206.                             text: 'Usage (%)'
  207.                         },
  208.                         min: 0,
  209.                         max: 100
  210.                     },
  211.                     series: [
  212.                         {
  213.                             name: 'Disk Usage',
  214.                             data: chartData.map(item => [item[0], item[1].diskUsage]),
  215.                             color: '#ffc107'
  216.                         }
  217.                     ]
  218.                 });
  219.                 break;
  220.                
  221.             case 'network':
  222.                 performanceChart.update({
  223.                     title: {
  224.                         text: 'Network I/O'
  225.                     },
  226.                     yAxis: {
  227.                         title: {
  228.                             text: 'MB/s'
  229.                         },
  230.                         min: 0
  231.                     },
  232.                     series: [
  233.                         {
  234.                             name: 'Network In',
  235.                             data: chartData.map(item => [item[0], item[1].networkIn]),
  236.                             color: '#17a2b8'
  237.                         },
  238.                         {
  239.                             name: 'Network Out',
  240.                             data: chartData.map(item => [item[0], item[1].networkOut]),
  241.                             color: '#6f42c1'
  242.                         }
  243.                     ]
  244.                 });
  245.                 break;
  246.         }
  247.     }
  248.    
  249.     // 更新图表数据
  250.     function updateChartWithNewData(newData) {
  251.         const timestamp = new Date(newData.timestamp).getTime();
  252.         
  253.         switch (currentChartType) {
  254.             case 'overview':
  255.                 // 更新CPU使用率
  256.                 updateSeriesData(0, timestamp, newData.cpuUsage);
  257.                 // 更新内存使用率
  258.                 updateSeriesData(1, timestamp, newData.memoryUsage);
  259.                 // 更新磁盘使用率
  260.                 updateSeriesData(2, timestamp, newData.diskUsage);
  261.                 break;
  262.                
  263.             case 'cpu':
  264.                 // 更新CPU使用率
  265.                 updateSeriesData(0, timestamp, newData.cpuUsage);
  266.                 break;
  267.                
  268.             case 'memory':
  269.                 // 更新内存使用率
  270.                 updateSeriesData(0, timestamp, newData.memoryUsage);
  271.                 break;
  272.                
  273.             case 'disk':
  274.                 // 更新磁盘使用率
  275.                 updateSeriesData(0, timestamp, newData.diskUsage);
  276.                 break;
  277.                
  278.             case 'network':
  279.                 // 更新网络输入
  280.                 updateSeriesData(0, timestamp, newData.networkIn);
  281.                 // 更新网络输出
  282.                 updateSeriesData(1, timestamp, newData.networkOut);
  283.                 break;
  284.         }
  285.     }
  286.    
  287.     // 更新系列数据
  288.     function updateSeriesData(seriesIndex, x, y) {
  289.         if (performanceChart.series[seriesIndex]) {
  290.             // 添加新数据点
  291.             performanceChart.series[seriesIndex].addPoint([x, y], true, false);
  292.             
  293.             // 限制显示的数据点数量,保持图表清晰
  294.             const maxPoints = 100;
  295.             if (performanceChart.series[seriesIndex].data.length > maxPoints) {
  296.                 performanceChart.series[seriesIndex].data[0].remove(false);
  297.             }
  298.         }
  299.     }
  300.    
  301.     // 显示错误信息
  302.     function showError(message) {
  303.         const alertDiv = document.createElement('div');
  304.         alertDiv.className = 'alert alert-danger alert-dismissible fade show';
  305.         alertDiv.innerHTML = `
  306.             ${message}
  307.             <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  308.         `;
  309.         
  310.         const container = document.querySelector('.container');
  311.         container.insertBefore(alertDiv, container.firstChild);
  312.         
  313.         // 3秒后自动关闭
  314.         setTimeout(() => {
  315.             alertDiv.classList.remove('show');
  316.             setTimeout(() => {
  317.                 alertDiv.remove();
  318.             }, 150);
  319.         }, 3000);
  320.     }
  321.    
  322.     // 初始加载数据
  323.     loadPerformanceData(currentChartType, formatDateTime(startTime), formatDateTime(endTime));
  324.    
  325.     // 更新图表按钮点击事件
  326.     document.getElementById('update-charts').addEventListener('click', function() {
  327.         const startTime = document.getElementById('start-time').value;
  328.         const endTime = document.getElementById('end-time').value;
  329.         
  330.         if (!startTime || !endTime) {
  331.             showError('Please select both start and end times.');
  332.             return;
  333.         }
  334.         
  335.         if (new Date(startTime) > new Date(endTime)) {
  336.             showError('Start time must be before end time.');
  337.             return;
  338.         }
  339.         
  340.         loadPerformanceData(currentChartType, startTime, endTime);
  341.     });
  342.    
  343.     // 标签页切换事件
  344.     document.getElementById('overview-tab').addEventListener('click', function(e) {
  345.         e.preventDefault();
  346.         currentChartType = 'overview';
  347.         document.querySelectorAll('.nav-link').forEach(link => {
  348.             link.classList.remove('active');
  349.         });
  350.         this.classList.add('active');
  351.         
  352.         const startTime = document.getElementById('start-time').value;
  353.         const endTime = document.getElementById('end-time').value;
  354.         loadPerformanceData(currentChartType, startTime, endTime);
  355.     });
  356.    
  357.     document.getElementById('cpu-tab').addEventListener('click', function(e) {
  358.         e.preventDefault();
  359.         currentChartType = 'cpu';
  360.         document.querySelectorAll('.nav-link').forEach(link => {
  361.             link.classList.remove('active');
  362.         });
  363.         this.classList.add('active');
  364.         
  365.         const startTime = document.getElementById('start-time').value;
  366.         const endTime = document.getElementById('end-time').value;
  367.         loadPerformanceData(currentChartType, startTime, endTime);
  368.     });
  369.    
  370.     document.getElementById('memory-tab').addEventListener('click', function(e) {
  371.         e.preventDefault();
  372.         currentChartType = 'memory';
  373.         document.querySelectorAll('.nav-link').forEach(link => {
  374.             link.classList.remove('active');
  375.         });
  376.         this.classList.add('active');
  377.         
  378.         const startTime = document.getElementById('start-time').value;
  379.         const endTime = document.getElementById('end-time').value;
  380.         loadPerformanceData(currentChartType, startTime, endTime);
  381.     });
  382.    
  383.     document.getElementById('disk-tab').addEventListener('click', function(e) {
  384.         e.preventDefault();
  385.         currentChartType = 'disk';
  386.         document.querySelectorAll('.nav-link').forEach(link => {
  387.             link.classList.remove('active');
  388.         });
  389.         this.classList.add('active');
  390.         
  391.         const startTime = document.getElementById('start-time').value;
  392.         const endTime = document.getElementById('end-time').value;
  393.         loadPerformanceData(currentChartType, startTime, endTime);
  394.     });
  395.    
  396.     document.getElementById('network-tab').addEventListener('click', function(e) {
  397.         e.preventDefault();
  398.         currentChartType = 'network';
  399.         document.querySelectorAll('.nav-link').forEach(link => {
  400.             link.classList.remove('active');
  401.         });
  402.         this.classList.add('active');
  403.         
  404.         const startTime = document.getElementById('start-time').value;
  405.         const endTime = document.getElementById('end-time').value;
  406.         loadPerformanceData(currentChartType, startTime, endTime);
  407.     });
  408.    
  409.     // 连接WebSocket
  410.     connect();
  411.    
  412.     // 在页面关闭时断开连接
  413.     window.addEventListener('beforeunload', function() {
  414.         disconnect();
  415.     });
  416.    
  417.     // 定期获取当前系统性能数据
  418.     setInterval(async function() {
  419.         try {
  420.             const response = await fetch('/api/performance/current');
  421.             if (!response.ok) {
  422.                 throw new Error('Network response was not ok');
  423.             }
  424.             
  425.             const data = await response.json();
  426.             updateCurrentMetrics(data);
  427.         } catch (error) {
  428.             console.error('Error fetching current performance data:', error);
  429.         }
  430.     }, 5000); // 每5秒更新一次
  431. });
复制代码

6.3 最佳实践

在将Highcharts与Spring Boot集成时,以下是一些最佳实践:

1. 前后端分离:保持前端和后端的清晰分离,使用RESTful API进行通信。
2. 数据格式化:在后端提供格式化良好的数据,减少前端处理负担。
3. 错误处理:实现全面的错误处理,包括网络错误、数据格式错误等。
4. 性能优化:使用分页和延迟加载处理大量数据实现数据缓存减少数据库查询使用WebSocket实现实时更新,避免轮询
5. 使用分页和延迟加载处理大量数据
6. 实现数据缓存减少数据库查询
7. 使用WebSocket实现实时更新,避免轮询
8. 安全性:实现适当的认证和授权防止SQL注入和XSS攻击使用HTTPS保护数据传输
9. 实现适当的认证和授权
10. 防止SQL注入和XSS攻击
11. 使用HTTPS保护数据传输
12. 可扩展性:设计可扩展的架构,便于添加新的图表类型使用配置而非硬编码值实现模块化设计
13. 设计可扩展的架构,便于添加新的图表类型
14. 使用配置而非硬编码值
15. 实现模块化设计
16. 用户体验:提供加载指示器实现响应式设计适应不同设备添加交互功能如缩放、悬停提示等
17. 提供加载指示器
18. 实现响应式设计适应不同设备
19. 添加交互功能如缩放、悬停提示等

前后端分离:保持前端和后端的清晰分离,使用RESTful API进行通信。

数据格式化:在后端提供格式化良好的数据,减少前端处理负担。

错误处理:实现全面的错误处理,包括网络错误、数据格式错误等。

性能优化:

• 使用分页和延迟加载处理大量数据
• 实现数据缓存减少数据库查询
• 使用WebSocket实现实时更新,避免轮询

安全性:

• 实现适当的认证和授权
• 防止SQL注入和XSS攻击
• 使用HTTPS保护数据传输

可扩展性:

• 设计可扩展的架构,便于添加新的图表类型
• 使用配置而非硬编码值
• 实现模块化设计

用户体验:

• 提供加载指示器
• 实现响应式设计适应不同设备
• 添加交互功能如缩放、悬停提示等

7. 总结与展望

7.1 总结

本文详细介绍了如何将Highcharts与Spring Boot完美融合,打造动态数据可视化解决方案。我们从环境搭建开始,逐步构建了一个完整的销售数据可视化系统,并扩展到了系统性能监控场景。通过这个解决方案,我们可以:

• 使用Spring Boot构建强大的后端服务
• 利用Highcharts创建美观、交互式的图表
• 通过WebSocket实现实时数据更新
• 设计响应式用户界面适应不同设备

7.2 展望

未来,我们可以进一步扩展这个解决方案:

1. 增强数据分析能力:集成机器学习算法进行预测分析添加更多数据聚合和统计功能
2. 集成机器学习算法进行预测分析
3. 添加更多数据聚合和统计功能
4. 提升用户体验:实现更丰富的交互功能添加自定义仪表板功能支持图表导出和报告生成
5. 实现更丰富的交互功能
6. 添加自定义仪表板功能
7. 支持图表导出和报告生成
8. 扩展应用场景:适用于更多业务领域如金融、物流、医疗等支持更多数据源如IoT设备、社交媒体等
9. 适用于更多业务领域如金融、物流、医疗等
10. 支持更多数据源如IoT设备、社交媒体等
11. 技术升级:采用微服务架构提高可扩展性使用容器化部署简化运维集成云服务提升可靠性
12. 采用微服务架构提高可扩展性
13. 使用容器化部署简化运维
14. 集成云服务提升可靠性

增强数据分析能力:

• 集成机器学习算法进行预测分析
• 添加更多数据聚合和统计功能

提升用户体验:

• 实现更丰富的交互功能
• 添加自定义仪表板功能
• 支持图表导出和报告生成

扩展应用场景:

• 适用于更多业务领域如金融、物流、医疗等
• 支持更多数据源如IoT设备、社交媒体等

技术升级:

• 采用微服务架构提高可扩展性
• 使用容器化部署简化运维
• 集成云服务提升可靠性

Highcharts与Spring Boot的结合为数据可视化提供了强大而灵活的解决方案。通过本文的指导,你已经掌握了从零开始构建动态数据可视化系统的关键技能,可以将其应用到实际项目中,实现数据驱动的决策支持。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

手机版|联系我们|小黑屋|TG频道|RSS |网站地图

Powered by Pixtech

© 2025-2026 Pixtech Team.

>