springboot项目在线程中调用service访问数据库

创建类ApplicationBeanFactory

package com.xxx.comm.ApplicationBeanFactory;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


public class ApplicationBeanFactory implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ApplicationBeanFactory.applicationContext == null) {
            ApplicationBeanFactory.applicationContext = applicationContext;

        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

}

配置在启动类中配置@Import(ApplicationBeanFactory.class)


import com.xxx.comm.ApplicationBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@SpringBootApplication
@Import(ApplicationBeanFactory.class)
@EnableTransactionManagement
public class DatafactoryHiveServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(DatafactoryHiveServiceApplication.class, args);
    }


}

在线程中调用service类来访问数据库

package com.xxx.util;

import com.xxx.comm.ApplicationBeanFactory;
import com.xxx.model.bo.HiveLogBO;
import com.xxx.service.HiveService;
import org.apache.hive.jdbc.HivePreparedStatement;

import java.sql.PreparedStatement;
import java.util.List;


public class LogRunnable implements Runnable {
    private final HivePreparedStatement hvePreparedStatement;
    private final HiveService hiveService;
    private final StringBuffer stringBuffer;
    private String hiveLogId;

    public LogRunnable(PreparedStatement preparedStatement, String hiveLogId) {
        this.hiveService = (HiveService) ApplicationBeanFactory.getBean("hiveService");
        this.hvePreparedStatement = (HivePreparedStatement) preparedStatement;
        this.stringBuffer = new StringBuffer();
        this.hiveLogId = hiveLogId;
    }

    @Override
    public void run() {
        try {
            HiveLogBO bo = new HiveLogBO();
            bo.setId(Long.valueOf(hiveLogId));
            while (hvePreparedStatement.hasMoreLogs()) {
                updateQueryLog(bo);
                Thread.sleep(3000L);
            }
        } catch (InterruptedException e) {
            e.getStackTrace();
        }
    }

    private void updateQueryLog(HiveLogBO bo) {
        try {
            List<String> queryLogs = hvePreparedStatement.getQueryLog();
            for (String queryLog : queryLogs) {

                System.out.println(queryLog);
                if (queryLog.contains("INFO  : The url to track the job:")) {
                    String applicationId = queryLog.substring(queryLog.indexOf("INFO  : The url to track the job:") + 34);
                    bo.setApplicationId(applicationId);
                    hiveService.updateHiveLogApplicationId(bo);
                }
                stringBuffer.append(queryLog);
                stringBuffer.append("\n");
            }
            bo.setContent(stringBuffer.toString());
            hiveService.updateHiveLog(bo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot使用多线程查询数据库非常简单,可以参考以下步骤: 1. 创建一个实现Runnable接口的类,用于执行数据库查询任务。 ```java public class QueryTask implements Runnable { private YourRepository yourRepository; public QueryTask(YourRepository yourRepository) { this.yourRepository = yourRepository; } @Override public void run() { List<YourEntity> result = yourRepository.findAll(); // 处理查询结果 } } ``` 2. 在Controller层或Service创建线程池,执行查询任务。 ```java @RestController public class YourController { @Autowired private YourRepository yourRepository; @GetMapping("/query") public String query() { ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { Runnable task = new QueryTask(yourRepository); executorService.execute(task); } executorService.shutdown(); return "查询任务已提交"; } } ``` 在上述代码,我们使用了Java线程池来管理多个线程,可以避免频繁地创建和销毁线程,提高了系统性能。通过调用`executorService.execute(task)`方法,可以将查询任务提交到线程线程池会自动分配线程执行任务。最后,调用`executorService.shutdown()`方法关闭线程池。 需要注意的是,在多线程查询数据库时,需要保证数据库连接是线程安全的,可以通过使用数据库连接池来实现。可以在`application.properties`文件配置连接池相关的参数,例如: ``` spring.datasource.url=<your-database-url> spring.datasource.username=<your-database-username> spring.datasource.password=<your-database-password> spring.datasource.driver-class-name=<your-database-driver> spring.datasource.hikari.maximum-pool-size=20 spring.datasource.hikari.minimum-idle=5 ``` 其,`hikari`是一个优秀的连接池框架,可以有效地管理数据库连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值