需求
线上展示的项目,在特定时间段重置数据库
其实就是在spring boot上的特定时间运行.sql
文件。
实践
使用定时注解,请记得在启动类添加注解@EnableScheduling
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @RestController @RequestMapping("/test") public class InitDatabaseController {
private Logger logger = LoggerFactory.getLogger(InitDatabaseController.class);
@Autowired private DataService dataService;
@GetMapping("/") @Scheduled(cron = "0 0 8,14 * * ? ") public RespBean resetDatabase(){ logger.info("【开始】重置数据库vhr的数据"); long start = System.currentTimeMillis(); if (!dataService.resetDataBase("vhrbck.sql")){ return RespBean.error("重置数据库失败!"); }
long end = System.currentTimeMillis();
String cost = "用时:" + (end - start) / 1000.0 + "秒"; logger.info("【结束】重置成功:" + cost); return RespBean.ok("重置数据库成功!", cost); } }
|
Service
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| @Service public class DataServiceImpl implements DataService { @Autowired private DataSource dataSource;
@Override public Boolean resetDataBase(String sqlScriptName) { Connection conn = null; try { conn = dataSource.getConnection(); ClassPathResource rc = new ClassPathResource(sqlScriptName); EncodedResource er = new EncodedResource(rc, StandardCharsets.UTF_8); ScriptUtils.executeSqlScript(conn, er, true, true, "--", ";", "/*", "*/");
return true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return false; } }
|
重置数据库的接口请求不能过于频繁,因此可以搭配 限制接口请求次数
方法来使用