开发喵星球

若依微服务版集成积木报表指南(297)

前提条件

确保已创建积木报表模块 ruoyi-jimureport

1. 添加依赖

首先,在 ruoyi-jimureport 模块的 pom.xml 文件中,为报表微服务模块加入积木报表所需的依赖:

<!-- JimuReport -->
<dependency>
    <groupId>org.jeecgframework.jimureport</groupId>
    <artifactId>jimureport-spring-boot-starter</artifactId>
    <version>1.5.6</version>
</dependency>

2. 执行初始化脚本

获取积木报表所需的 SQL 脚本,地址:https://github.com/jeecgboot/JimuReport/tree/master/db 并执行。

3. 配置启动类

在报表微服务的启动类中,添加积木报表的扫描目录注解:

package com.ruoyi.report;

import com.ruoyi.common.security.annotation.EnableCustomConfig;
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;

/**
 * 报表中心模块启动类
 */
@EnableCustomConfig
@EnableCustomSwagger2
@EnableRyFeignClients
@SpringBootApplication(exclude = {MongoAutoConfiguration.class},
        scanBasePackages = {"org.jeecg.modules.jmreport", "com.ruoyi.report"})
public class ruoyiJimuReportApplication {

    public static void main(String[] args) {
        SpringApplication.run(ruoyiJimuReportApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" +
                " .-------.       ____     __        \n" +
                " |  _ _   \\      \\   \\   /  /    \n" +
                " | ( ' )  |       \\  _. /  '       \n" +
                " |(_ o _) /        _( )_ .'         \n" +
                " | (_,_).' __  ___(_ o _)'          \n" +
                " |  |\\ \\  |  ||   |(_,_)'         \n" +
                " |  | \\ `'   /|   `-'  /           \n" +
                " |  |  \\    /  \\      /           \n" +
                " ''-'   `'-'    `-..-'              ");
    }
}

4. 配置积木报表数据源

通过代码方式设置数据源:

package com.ruoyi.report.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

/**
 * 数据源配置类
 */
@Configuration
public class DataSourceConfig {
    /**
     * bean 的名称必须为 minidaoDataSource,才能生效。
     * jeecg.minidao-datasource 对应 yml 文件中的 jeecg 下的 minidao-datasource,可自定义。
     */
    @Bean(name = "minidaoDataSource")
    @ConfigurationProperties(prefix = "jeecg.minidao-datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
}

5. 配置报表微服务

nacos 中新建 ruoyi-report-dev.yml 配置文件:

以下是完整的配置:

# spring 配置
spring:
  redis:
    host: 119.91.201.150
    port: 6379
    password: 

# Minidao 配置
minidao:
  base-package: org.jeecg.modules.jmreport.*

jeecg:
  minidao-datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    jdbc-url: jdbc:mysql://119.91.202.150:3306/ry-cloud?characterEncoding=UTF-8&autoReconnect=true&serverTimezone=GMT%2b8
    username: 
    password: 
    hikari:
      maximum-pool-size: 400
      minimum-idle: 20
      idle-timeout: 30000
      connection-timeout: 1800000
      max-lifetime: 1800000
  jmreport:
    saas: false
    exportDisabled: false
    autoSave: false
    interval: 20000
    col: 300
    customPrePath: /report
    pageSize:
      - 10
      - 20
      - 50
      - 100
    printPaper:
      - title: 标签打印
        size:
          - 140
          - 100        
    connect-timeout: 1800000
    export-excel-pattern: fast
    page-size-number: 1048576
    excel-style-row: 1048576
    viewToolbar:
    ```yml
    viewToolbar: true
    line: true
    select-show-total: 10  

# MyBatis 配置
mybatis:
    typeAliasesPackage: com.ruoyi.report
    mapperLocations: classpath:mapper/**/*.xml

# Knife4j 配置
knife4j:
  enable: true
#   basic:
#     enable: true
#     username: 
#     password: 

# Swagger 配置
swagger:
  version: 1.0.0
  title: 报表中心接口文档
  basePackage: com.ruoyi.report
  termsOfServiceUrl: ruoyi-center
  description: 报表中心系统接口的说明文档
  contact:
    name: xxx

注意事项
customPrePath 路径配置需与网关的断言配置保持一致,否则可能无法正确路由。

6. 配置网关微服务

ruoyi-gateway-dev.yml 配置文件中为报表微服务添加路由规则:

routes:
    # 报表中心服务
    - id: ruoyi-report
      uri: lb://ruoyi-report
      predicates:
        - Path=/report/**
      filters:
        - StripPrefix=1

同样,在 ruoyi-gateway-dev.yml 文件中,配置积木报表的安全设置,并将其加入白名单:

# 安全配置
security:
  # 验证码
  captcha:
    enabled: true
    type: math
  # 防止XSS攻击
  xss:
    enabled: true
    excludeUrls:
      - /system/notice
      - /report/jmreport/**
  # 不校验白名单
  ignore:
    whites:
      - /auth/logout
      - /auth/login
      - /auth/register
      - /*/v2/api-docs
      - /csrf
      - /message/websocket/**
      - /report/**

7. 扩展:Token 权限控制

为了对报表服务进行 Token 验证,可以自定义 Token 服务类:

package com.ruoyi.report.jimureport.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import org.jeecg.modules.jmreport.api.JmReportTokenServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义报表鉴权服务实现
 */
@Component
public class JimuReportTokenServiceImpl implements JmReportTokenServiceI {

    @Autowired
    private TokenService tokenService;

    /**
     * 获取 Token
     */
    @Override
    public String getToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (token == null || token.isEmpty()) {
            token = request.getHeader("token");
        }
        LoginUser loginUser = tokenService.getLoginUser(token);
        return (loginUser != null) ? token : "";
    }

    /**
     * 获取用户名
     */
    @Override
    public String getUsername(String token) {
        LoginUser loginUser = tokenService.getLoginUser(token);
        return loginUser.getUsername();
    }

    /**
     * 校验 Token
     */
    @Override
    public Boolean verifyToken(String token) {
        if (token != null && !token.isEmpty()) {
            LoginUser loginUser = tokenService.getLoginUser(token);
            return loginUser != null;
        }
        return false;
    }

    /**
     * 自定义请求头
     */
    @Override
    public HttpHeaders customApiHeader() {
        HttpHeaders header = new HttpHeaders();
        header.add("X-Access-Token", tokenService.getToken());
        return header;
    }

    /**
     * 获取多租户 ID
     */
    @Override
    public String getTenantId() {
        String token = SecurityUtils.getCurrentRequestInfo().getParameter("token");
        String header = SecurityUtils.getCurrentRequestInfo().getHeader("X-Access-Token");
        LoginUser loginUser = (token != null) ? tokenService.getLoginUser(token) : tokenService.getLoginUser(header);

        if (loginUser == null) {
            return "NO";
        }

        // 若具备管理员权限,可访问所有报表
        if (SecurityUtils.isAdmin(loginUser.getUserid())
                || loginUser.getRoles().contains("it")
                || loginUser.getRoles().contains("manager")) {
            return "";
        }
        return loginUser.getUsername();
    }

    /**
     * 获取用户信息
     */
    @Override
    public Map<String, Object> getUserInfo(String token) {
        Map<String, Object> userInfo = new HashMap<>(20);
        LoginUser loginUser = tokenService.getLoginUser(token);
        userInfo.put("sysUserCode", loginUser.getUsername());
        userInfo.put("sysData", DateUtils.getDate());
        userInfo.put("sysYesterDay", DateUtils.getYesterday());
        userInfo.put("sysUserName", loginUser.getSysUser().getNickName());
        userInfo.put("deptId", loginUser.getSysUser().getDeptId());
        userInfo.put("describe", loginUser.getSysUser().getDept().getRemark());
        return userInfo;
    }
}

8. 前端页面配置

在前端项目中新建 jimureport 文件夹,并添加以下两个 vue 文件。

1. jmreport.vue

<template>
  <i-frame :src="openUrl" id="jimuReportFrame"></i-frame>
</template>
<script>
  import { getToken } from '@/utils/auth'
  import iFrame from '@/components/iFrame/index'
  export default {
    name: "jimu",
    components: {iFrame},
    data() {
      return {
        // 替换为暴露的统一网关地址
        openUrl: "http://127.0.0.1:8080/report/jmreport/list?token=" + getToken(),
      };
    },
  };
</script>

2. view.vue

<template>
  <i-frame :src="openUrl"/>
</template>

<script>
import {getToken} from '@/utils/auth'
import iFrame from "@/components/iFrame/index";

export default {
  name: 'jimuview',
  components: {iFrame},
  props: {
    reportID: {
      type: [String],
      required: false,
      default: ''
    },
  },
  data() {
    return {
      serverUrl: 'http://127.0.0.1:8080',
      openUrl: '',
    }
  },
  created() {
    this.openUrl = this.serverUrl + '/report/jmreport/view/' + (this.reportID || this.$route.path.split("/").pop()) + '?token=' +  getToken();
  }
}
</script>

9. 配置报表菜单

运行若依管理系统,添加一个新目录,设置路由地址为 jimu。在该目录下新增菜单项,路由地址为 design,组件路径为 jimureport/jimu,权限字符为 report:jimu:list

这篇文章内容已经进行了改写,保持了原意但使用了不同的描述方式。

   
分类:Java/OOP 作者:无限繁荣, 吴蓉 发表于:2024-08-12 09:32:48 阅读量:130
<<   >>


powered by kaifamiao