每秒将数据保存到db以解决丢失或缓慢的数据库连接问题

时间:2018-01-09 17:58:09

标签: java mysql spring multithreading spring-data-jpa

我正在使用spring数据jpa和mysql编写java控制台应用程序,我正在尝试解决以下情况:

App每秒生成一个新对象,应该以相同的顺序同时保存到db。如果数据库连接丢失或者在对象保存期间长时间调用超时异常,则将即将到来的对象保存到临时缓冲区。当连接将被恢复时,将所有这些累积的对象和新的即将生成的对象(在该特定时刻)保存到db。

我的问题是:

  • 当数据库连接丢失时,如何处理在临时缓冲区中保存对象?

我想我应该在数据库连接丢失时使用ScheduledExecutorService捕获Throwable,然后将特定对象保存到CopyOnWriteArrayList,这是正确的方法吗?

  • 如何在连接丢失时停止将新对象保存到数据库中,以前的对象保存调用超时异常并在连接启动时保存即将出现的对象的恢复过程?
  • 在保存新生成的对象之前,如何在连接启动时将所有累积的对象保存到db?

更新

我编写了使用上述行为运行对象生成的服务:

服务

@Service
public class ReportService implements IReportService {

  @Autowired
  private ReportRepository reportRepository;

  @Override
  public void generateTimestamps() {

    BlockingQueue<Report> queue = new LinkedBlockingQueue<>();
    new Thread(new ReportsProducer(queue)).start();
    new Thread(new ReportsConsumer(queue, reportRepository)).start();
  }

  @Override
  public List<Report> showTimestamps() {
    return reportRepository.findAll();
  }
}

对象制作人:

public class ReportsProducer implements Runnable {

  private final BlockingQueue<Report> reportsQueue;

  ReportsProducer(BlockingQueue<Report> numbersQueue) {
    this.reportsQueue = numbersQueue;
  }

  public void run() {
    try {
      while (true) {
        generateReportEverySecond();
      }
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }

  private void generateReportEverySecond() throws InterruptedException {
    Thread.sleep(1000);
    Report report = new Report();
    reportsQueue.put(report);
    System.out.println(Thread.currentThread().getName() + ": Generated report[id='" + report.getId() + "', '" + report
            .getTimestamp() + "']");
  }
}

对象消费者:

public class ReportsConsumer implements Runnable {
  private final BlockingQueue<Report> queue;

  private ReportRepository reportRepository;

  ReportsConsumer(BlockingQueue<Report> queue, ReportRepository reportRepository) {
    this.queue = queue;

//    Not sure i do this correct way
    this.reportRepository = reportRepository;
  }

  public void run() {
    while (true) {
      try {
        if (!queue.isEmpty()) {
          System.out.println("Consumer queue size: " + queue.size());

          Report report = reportRepository.save(queue.peek());
          queue.poll();
          System.out.println(Thread.currentThread().getName() + ": Saved report[id='" + report.getId() + "', '" + report
                  .getTimestamp() + "']");
        }

      } catch (Exception e) {

        //  Mechanism to reconnect to DB every 5 seconds
        try {
          System.out.println("Retry connection to db");
          Thread.sleep(5000);
        } catch (InterruptedException e1) {
          e1.printStackTrace();
        }
      }
    }
  }
}

存储库:

@Repository
public interface ReportRepository extends JpaRepository<Report, Long> {
}

对象

@Entity
@Table(name = "reports")
public class Report {

  @Id
  @GeneratedValue
  private Long id;

  @Column
  private Timestamp timestamp;

  public Report() {
    this.timestamp = new Timestamp(new Date().getTime());
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public Timestamp getTimestamp() {
    return timestamp;
  }

  public void setTimestamp(Timestamp timestamp) {
    this.timestamp = timestamp;
  }
}

Application.properties:

spring.datasource.url=jdbc:mysql://xyz:3306/xyz
spring.datasource.username=xyz
spring.datasource.password=xyz

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.ddl-auto = create-drop

# Below properties don't work actually
spring.jpa.properties.javax.persistence.query.timeout=1
# Reconnect every 5 seconds
spring.datasource.tomcat.test-while-idle=true
spring.datasource.tomcat.time-between-eviction-runs-millis=5000
spring.datasource.tomcat.validation-query=SELECT 1

的build.gradle:

version '1.0'

buildscript {
    ext {
        springBootVersion = '1.5.9.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

ext {
    mysqlVersion = '6.0.6'
    dbcp2Version = '2.2.0'
    hibernateVersion = '5.2.12.Final'
}

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'mysql', name: 'mysql-connector-java', version: mysqlVersion
    compile group: 'org.hibernate', name: 'hibernate-core', version: hibernateVersion
    compile group: 'org.hibernate', name: 'hibernate-c3p0', version: hibernateVersion
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    testCompile("org.springframework.boot:spring-boot-starter-test")
    compile group: 'org.assertj', name: 'assertj-core', version: '3.9.0'
}

根据以上代码,我想知道一些时刻:

  • 您建议如何检查数据库连接?

    我使用保存操作来检查,如果数据库连接丢失我只等待5秒并重复操作。此外,数据源配置为每隔5秒就建立数据库连接(如果它已关闭)。有没有更正确的方法呢?

  • 如果db连接处于活动状态但db目前非常慢或太忙(ovberloaded)会发生什么?

    据我所知,我需要为查询设置超时。在这种情况下我还应该做些什么呢?

2 个答案:

答案 0 :(得分:1)

对于前三个问题,您正在寻找Queue。如果您使用的是Spring框架,它会为JPA使用单个类,因为RepositoryBean,只要您正确配置它,Spring就会为您处理数据库连接池。

  1. 您建议如何检查数据库连接?

    您在application.properties中所做的工作确实检查了连接性。我认为5000毫秒太频繁,它可能会减慢您的系统速度。 360000可能是一个很好的间隔。

  2. 如果db连接处于活动状态但db目前非常慢或太忙(ovberloaded)会发生什么?

    配置连接池时,可以设置以下属性:

    removeAbandoned - set to true if we want to detect leaked connections

    removeAbandonedTimeout - the number of seconds from when dataSource.getConnection was called to when we consider it abandoned

    logAbandoned - set to true if we should log that a connection was abandoned. If this option is set to true, a stack trace is recorded during the dataSource.getConnection call and is printed when a connection is not returned

  3. 参考:Configuring jdbc-pool for high-concurrency

答案 1 :(得分:0)

IMO,每隔5秒检查一次数据库连接应该不是一个好主意,而是你的数据库超载了一些不必要的请求。正如@TopDeck所提到的,你应该使用Queue实现connection pooling(你不应该通过创建添加新对象的新连接来重载数据库)