package cn.quantgroup.customer.config.data;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DatabaseConnectionKeeper {

    private EntityManager entityManager;

    @Autowired
    public DatabaseConnectionKeeper(@Qualifier("entityManagerSecondary") EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    // 每一分钟执行一次查询操作，保持数据库连接活跃
    @Scheduled(fixedDelay = 60000)
    public void keepDatabaseConnectionAlive() {
        try {
            // 执行一个简单的查询操作
            Query countQuery = entityManager.createNativeQuery("SELECT 1");
            Object count = countQuery.getSingleResult();
        } catch (Exception ex) {
            // 处理异常
            log.error("保持数据库连接活跃定时任务执行异常",ex);
        }
    }
}