spring boot 实战小试
最近遇到个很尴尬的问题,就是服务器上的程序留下日志文件记得太多,而且也没有清除,居然把硬盘塞满了,然后程序就死了。真的尴尬呀,手动清除了一下过期没用的日志,重新启动就ok了。问题虽然是解决了,但真的是太尴尬了,日志只记不管,迟早还是会被塞满,程序还会在不知道什么时候又会死。所以呢,不如写一个小程序,设定一下保存多少天的日志,定期清除不需要的日志。正好最近在学习研究spring boot ,据说这spring boot 号称开箱即用,简化复杂配置,那就试一下吧。
这是我的spring boot 目录结构:
application.properoties的配置
#要清除的根目录,多个目录用‘|’隔开
com.sundyn.gaox.cleanRoot=d:/logs|D:/repository
#清除10天以前的文件
com.sundyn.gaox.cleanDay=10
#程序日志记录生成路径
logging.file=d:/logs/cleanFile/cleanFile.log
name=gaoxing
banner.txt是什么呢?spring boot 启动的时候会出如下图的启动标志
再来看看我的启动标志
是不是很意思,哈哈,秘密就在banner.txt里,给大家推荐一个生成个性字符的工具:http://patorjk.com/software/taag,把生成的字符放在resources目录下的banner.txt里项目启动的时候就能看到了。
定期清除过期的日志,主要就是用到spring的定时调度,很简单。spring boot启用调度就更简单了,首先你要在启动类的上面加一个注解@EnableScheduling,然后在你的调度执行方法上,加上注解@Scheduled(fixedDelay=1000*24*60*60),来注明调度执行的条件,这里fixedDelay=1000*24*60*60就表示这个方法每隔24小时就会执行一次,当然还有其他的方法,这里因为只是定期清除一下失效日志,对时间的要求并没有那么严格,所以越简单越好了,当然如果你的需求要求控制执行的时间非常精确,可以用复杂一点表达式,或者用更专业的一些框架等其他方法,总之做什么东西满足需求的情况下,越简单越好,没必要整的很复杂。
主要的类如下:
启动类CleanFileApplication.java:
package com.sundyn.gaox;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class CleanFileApplication {
publicstatic void main(String[] args) {
SpringApplication.run(CleanFileApplication.class,args);
}
}
封装实体类FileResult.java:
package com.sundyn.gaox.task;
import java.io.File;
import java.util.Date;
public class FileResult {
privateFile file;
privateString name;
privateDate createTime;
privateString path;
publicString getName() {
returnname;
}
publicvoid setName(String name) {
this.name= name;
}
publicDate getCreateTime() {
returncreateTime;
}
publicvoid setCreateTime(Date createTime) {
this.createTime= createTime;
}
publicFile getFile() {
returnfile;
}
publicvoid setFile(File file) {
this.file= file;
}
publicString getPath() {
returnpath;
}
publicvoid setPath(String path) {
this.path= path;
}
}
文件工具类FileUtil.java,主要用来获取目录下的所有文件和文件的创建时间:
package com.sundyn.gaox.task;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class FileUtil {
private static Set<File> set=new HashSet<File>();
/**
* 获取根目录包括根目录下所有子目录下的所有文件
* @paramfile
* @return
*/
public static Set<File> queryRoot(File file){
if(file.isDirectory()){
File[]files=file.listFiles();
for (Filefile2 : files) {
if(file2.isDirectory()){
queryRoot(file2);
}else{
set.add(file2);
}
}
}else{
set.add(file);
}
return set;
}
/**
* 获取文件的创建时间
* @param fullFileName
* @return
*/
public static Date getCreateTime(String fullFileName){
Path path=Paths.get(fullFileName);
BasicFileAttributeView basicview=Files.getFileAttributeView(path,BasicFileAttributeView.class,LinkOption.NOFOLLOW_LINKS );
BasicFileAttributes attr;
try {
attr = basicview.readAttributes();
Date createDate = new Date(attr.creationTime().toMillis());
returncreateDate;
} catch (Exceptione) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.set(1970, 0, 1, 0, 0, 0);
returncal.getTime();
}
}
任务类CleanTask.java:
package com.sundyn.gaox.task;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
importjava.nio.file.attribute.BasicFileAttributeView;
importjava.nio.file.attribute.BasicFileAttributes;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.scheduling.annotation.Scheduled;
importorg.springframework.stereotype.Component;
@Component
public class CleanTask {
@Value("${name}")
privateString name;
@Value("${com.sundyn.gaox.cleanRoot}")
privateString rootStr;
@Value("${com.sundyn.gaox.cleanDay}")
privateint cleanDay;
privateLogger log=Logger.getLogger(CleanTask.class);
@Scheduled(fixedDelay=1000*10)
publicvoid clean(){
// Integerseconds=cleanDay*24*60*60*1000;
Integerseconds=1000*10;
String[]roots=rootStr.split("\\|");
for(String root : roots) {
Set<FileResult>list=this.getFileResults(root);
for(FileResult fileResult : list) {
Datedate=new Date(new Date().getTime()-seconds);
if(fileResult.getCreateTime().getTime()<date.getTime()){
Filefile=fileResult.getFile();
if(file.exists()){
file.delete();
log.info("success->delete:"+fileResult.getFile().getPath()+">>>[createTime:"+newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(fileResult.getCreateTime())+"]");
}
}
}
}
}
publicSet<FileResult> getFileResults(String root){
Set<FileResult>set=new HashSet<FileResult>();
Set<File>fileList=FileUtil.queryRoot(new File(root));
for(File file : fileList) {
FileResult fileResult=new FileResult();
fileResult.setFile(file);
fileResult.setCreateTime(FileUtil.getCreateTime(file.getPath()));
fileResult.setName(file.getName());
fileResult.setPath(file.getPath());
set.add(fileResult);
}
returnset;
}
}
pom.xml文件:
<?xmlversion="1.0"encoding="UTF-8"?>
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sundyn.gaox</groupId>
<artifactId>com.sundyn.gaox.cleanFile</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>cleanFile</name>
<description>create bygaox</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/><!-- lookup parent from repository-->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>cleanFile</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
小试了一把,不得不说,还真是开箱即用,配置简单。最近公司要由svn改用git了,码云开通很久了,一直没用过,正好,传到码云上练练手,对git 和spring boot有兴趣的小伙们可以去码云上https://gitee.com/fox9916/cleanFile.git下载源码参考一下。