您的 Spring Boot 服务在 MySQL 命令行客户端开启后才能正常运行,这表明服务对 MySQL 数据库的依赖关系存在问题。
# Linux (systemd)
sudo systemctl enable mysql
sudo systemctl start mysql
# Windows
# 确保 MySQL 服务设置为自动启动
在 application.properties
或 application.yml
中:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 添加连接池配置
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.maximum-pool-size=5
在 pom.xml
中添加重试依赖:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
然后在启动类上添加注解:
@EnableRetry
@SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
@Lazy
@Service
public class SomeService {
// 依赖于数据库的服务
}
@Component
public class DatabaseHealthChecker implements ApplicationRunner {
@Autowired
private DataSource dataSource;
@Override
public void run(ApplicationArguments args) throws Exception {
try (Connection conn = dataSource.getConnection()) {
// 测试连接
} catch (Exception e) {
throw new IllegalStateException("无法连接到数据库", e);
}
}
}
logging.level.org.springframework.jdbc=DEBUG
logging.level.com.zaxxer.hikari=DEBUG
如果问题仍然存在,请提供具体的错误日志以便进一步分析。