简介

ureport是一个比较强大的开源免费报表工具,在原有功能基础之上,本文使用nacos作为配置中心,支持多个主库的数据查询操作,进一步拓展ureport的功能。

环境信息

数据库信息

  1. dating数据库有一张活动表activity,里面有141条记录
  2. dating_jb数据库有一张job职位表,里面有1条记录

现在要实现在同一个工程下,根据mapper的路径不同,支持查询两个数据库的数据。

pom依赖

nacos对springboot版本有要求,具体可以去看nacos文档。
nacos文档地址

<parent>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>2.1.14.RELEASE</version>
	    <relativePath/> <!-- lookup parent from repository -->
</parent>

<modelVersion>4.0.0</modelVersion>
<groupId>com.test.admin</groupId>
<artifactId>ureport</artifactId>
<version>1.0</version>
<name>ureport</name>

<dependencies>
        <dependency>
	      <groupId>com.alibaba.cloud</groupId>
	      <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
	      <version>2.1.2.RELEASE</version>
	      <scope>compile</scope>
    	</dependency>
    	
    	<dependency>
	      <groupId>com.alibaba.cloud</groupId>
	      <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
	      <version>2.1.2.RELEASE</version>
	      <scope>compile</scope>
    	</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!--ureport-->
        <dependency>
            <groupId>com.syyai.spring.boot</groupId>
            <artifactId>ureport-spring-boot-starter</artifactId>
            <version>2.2.9</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

ureport配置

config.properties

# 设置ureport报表存储路径
# ureport.fileStoreDir=D:/ureportfiles
# 是否隐藏ureport自带的报表存储方式
ureport.disableFileProvider=false

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">

    <!-- 引入ureport2报表xml配置文件 -->
    <import resource="classpath:ureport-console-context.xml" />

    <!-- 修改目录文件位置。这里多说几句,官方文档默认是在/WEB-INF/config.properties下面,
    WEB-INF每次运行的时候都会动态生成一个临时目录,我们是找不到的,所以我们将位置修改成绝对路径,自己可以找到。
    由于config.properties是在resouces配置下,所以使用classpath: -->
    <bean id="propertyConfigurer" parent="ureport.props">
        <property name="location">
            <value>classpath:config.properties</value>
        </property>
    </bean>

</beans>

启动类配置

ureport内置了默认数据源,后面我们

@SpringBootApplication
@ImportResource("classpath:context.xml")
public class UReportApplication {

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

	/*可以放到另外一个配置类中*/
    @Bean
    public ServletRegistrationBean ureportServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new UReportServlet());
        bean.addUrlMappings("/ureport/*");
        return bean;
    }
}

nacos服务端配置

注意nacos命名规则即可。

springboot整合quartz持久化 springboot整合ureport_spring

在nacos上配置数据源信息,分order订单数据源和service其它业务数据源

spring:
  order:
    username: taohulu
    password: taohulu-dev
    url: jdbc:mysql://120.17.31.7:3306/dating?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
    driver-class-name: com.mysql.cj.jdbc.Driver
  service:
    username: taohulu
    password: taohulu-dev
    url: jdbc:mysql://120.17.31.7:3306/_dating_job?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull
    driver-class-name: com.mysql.cj.jdbc.Driver

java中引入nacos配置信息

nacos配置必须放在bootstrap.yml中,否则会报错,原因是nacos相关配置信息要早于其他配置文件的加载。

spring:
  cloud:
    nacos:
      username: nacos
      password: nacos
      config:
        namespace: 77eed108-e1ea-4764-8030-c54f28272abe
        # nacos配置中心服务器地址
        server-addr: 10.1.20.5:8848
        file-extension: yml
      discovery:
      	# nacos注册中心服务器地址
        server-addr: 10.1.20.5:8848
  application:
    name: seed-universalcard-ureport
  profiles:
    active: dev
  main:
    allow-bean-definition-overriding: true
server:
  port: 10081

定义nacos配置类

nacos配置在程序启动的时候就已经加入到springboot环境中,因此获取配置信息的方式,和在本地配置一样。

@Component
@Data
@RefreshScope
public class NacosConfig {
	
	// 获取nacos配置示例
	@Value("${spring.order.username}")
    private String name;
}```

#  结合ureport规则定义多数据源
##  自定义order数据源

```java
@Configuration
@MapperScan(basePackages = "com.admin.ureport.mapper.order", sqlSessionTemplateRef ="orderSqlSessionTemplate")
@ConfigurationProperties(prefix = "spring.order")
@Data
public class OrderDataSource {

    private String url;

    private String username;

    private String password;

    private String driverClassName;

    /**本数据源扫描的mapper路径*/
    static final String MAPPER_LOCATION = "classpath:mapper/order/*.xml";

    @Bean(name = "orderSource")
    public DataSource getFirstDataSource() {
        DataSource build =  DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(url)
                .username(username)
                .password(password)
                .build();
        return build;
    }


    @Bean(name = "orderSqlSessionFactory")
    @Primary
    public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mapper配置文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return bean.getObject();
    }

    @Bean("orderTransactionManger")
    @Primary
    public DataSourceTransactionManager orderDataSourceTransactionManger(@Qualifier("orderSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "orderSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

自定义spring数据源

自定义service数据源

@Configuration
@MapperScan(basePackages = "com.admin.ureport.mapper.service", sqlSessionTemplateRef ="serviceSqlSessionTemplate")
@ConfigurationProperties(prefix = "spring.service")
@Data
public class ServiceDataSource {

    private String url;

    private String username;

    private String password;

    private String driverClassName;

    /**本数据源扫描的mapper路径*/
    static final String MAPPER_LOCATION = "classpath:mapper/service/*.xml";

    @Bean(name = "serviceSource")
    public DataSource getFirstDataSource() {
        DataSource build =  DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(url)
                .username(username)
                .password(password)
                .build();
        return build;
    }


    @Bean(name = "serviceSqlSessionFactory")
    @Primary
    public SqlSessionFactory orderSqlSessionFactory(@Qualifier("serviceSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mapper配置文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return bean.getObject();
    }

    @Bean("serviceTransactionManger")
    @Primary
    public DataSourceTransactionManager orderDataSourceTransactionManger(@Qualifier("serviceSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "serviceSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("serviceSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

自定义order数据源

@Configuration
@MapperScan(basePackages = "com.admin.ureport.mapper.order", sqlSessionTemplateRef ="orderSqlSessionTemplate")
@ConfigurationProperties(prefix = "spring.order")
@Data
public class OrderDataSource {

    private String url;

    private String username;

    private String password;

    private String driverClassName;

    /**本数据源扫描的mapper路径*/
    static final String MAPPER_LOCATION = "classpath:mapper/order/*.xml";

    @Bean(name = "orderSource")
    public DataSource getFirstDataSource() {
        DataSource build =  DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(url)
                .username(username)
                .password(password)
                .build();
        return build;
    }


    @Bean(name = "orderSqlSessionFactory")
    @Primary
    public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mapper配置文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return bean.getObject();
    }

    @Bean("orderTransactionManger")
    @Primary
    public DataSourceTransactionManager orderDataSourceTransactionManger(@Qualifier("orderSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "orderSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

自定义ureport数据源

自定义ureport-order数据源

@Slf4j
@Component
public class UreportOrderDataSource implements BuildinDatasource {
    private static final String NAME = "订单数据源";

    @Resource(name="orderSource")
    private DataSource dataSource;

    @Override
    public String name() {
        return NAME;
    }

    @Override
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            log.error("Ureport 数据源 获取连接失败!");
            e.printStackTrace();
        }
        return null;
    }
}

自定义ureport-service数据源

@Slf4j
@Component
public class UreportServiceDataSource implements BuildinDatasource {
    private static final String NAME = "业务数据源";

    @Resource(name="serviceSource")
    private DataSource dataSource;

    @Override
    public String name() {
        return NAME;
    }

    @Override
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            log.error("Ureport 数据源 获取连接失败!");
            e.printStackTrace();
        }
        return null;
    }
}

创建mapper

com.admin.ureport.mapper.service路径下创建ServiceMapper

public interface ServiceMapper {

    Integer getCount();
}

com.admin.ureport.mapper.order路径下创建OrderMapper

public interface OrderMapper {

    Integer getActivity();
}

创建controller

因为是demo,使用不要在意分层了

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    OrderMapper orderMapper;

    @Resource
    ServiceMapper serviceMapper;

    @RequestMapping("/getActivity")
    public Integer getActivity() {
        return orderMapper.getActivity();
    }

    @RequestMapping("/getCount")
    public Integer getCount() {
        return serviceMapper.getCount();
    }
}

结果演示

发现可以成功连接上两个数据库源,并可以预览数据。

springboot整合quartz持久化 springboot整合ureport_xml_02