一、springBoot开发定时任务
①:连接数据库实现新增功能
1. 引入依赖
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version>
</dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.0</version>
</dependency>
2. 配置yaml
server:port: 19000 # ????????spring:application:name: djyp-stater # ???????datasource:url: jdbc:mysql://ip地址:3306/djyp?characterEncoding=UTF-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 密码driver-class-name: com.mysql.cj.jdbc.Driver
3. 创建实体类
@Entity
@Table (name = "log", schema = "djyp", catalog = "")
public class LogEntity {@GeneratedValue (strategy = GenerationType.IDENTITY)@Id@Column (name = "id")private long id;@Basic@Column (name = "create_time")private Date createTime;@Basic@Column (name = "status")private Integer status;public long getId () {return id;}public void setId (long id) {this.id = id;}public Date getCreateTime () {return createTime;}public void setCreateTime (Date createTime) {this.createTime = createTime;}public Integer getStatus () {return status;}public void setStatus (Integer status) {this.status = status;}@Overridepublic boolean equals (Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;LogEntity logEntity = (LogEntity) o;return id == logEntity.id && Objects.equals(createTime, logEntity.createTime) && Objects.equals(status, logEntity.status);}@Overridepublic int hashCode () {return Objects.hash(id, createTime, status);}
}
4. 创建mapper执行SQL
@Mapper
public interface LogMapper{@Insert("insert into log(create_time) values (#{date})")int add (@Param("date") Date date);
}
②:配置logback日志
1. 引入依赖 配置yml
<!-- 引入日志框架 -->
<dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId>
</dependency>
logging:level:com.example: infopattern:console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
2. 创建日志配置类
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.color.ANSIConstants;
import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase;public class LogbackColorful extends ForegroundCompositeConverterBase<ILoggingEvent> {@Overrideprotected String getForegroundColorCode(ILoggingEvent event) {Level level = event.getLevel();switch (level.toInt()) {//ERROR等级为红色case Level.ERROR_INT:return ANSIConstants.RED_FG;//WARN等级为黄色case Level.WARN_INT:return ANSIConstants.YELLOW_FG;//INFO等级为蓝色case Level.INFO_INT:return ANSIConstants.BLUE_FG;//DEBUG等级为绿色case Level.DEBUG_INT:return ANSIConstants.GREEN_FG;//其他为默认颜色default:return ANSIConstants.DEFAULT_FG;}}
}
3. 配置xml文件(logback-spring.xml)
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false"><!--自定义颜色配置 此处converterClass引用的是日志颜色类的路径, 此匹配的是第二种控制台色彩输出方式--><conversionRule conversionWord="customcolor" converterClass="com.sanss.djyp.config.LogbackColorful"/><appender name="consoleLog" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%red(%d{HH:mm:ss.SSS}) %green([%thread]) %customcolor(%-5level) %customcolor(%logger) - %msg%n</pattern></encoder></appender><appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender"><filter class="ch.qos.logback.classic.filter.LevelFilter"><level>DEBUG</level><onMatch>DENY</onMatch><onMismatch>ACCEPT</onMismatch></filter><encoder><pattern> %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n</pattern></encoder><!--滚动策略--><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!--路径--><fileNamePattern>logs/logbackInfo.%d.log</fileNamePattern></rollingPolicy></appender><appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender"><filter class="ch.qos.logback.classic.filter.ThresholdFilter"><level>DEBUG</level></filter><encoder><pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n</pattern></encoder><!--滚动策略--><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!--路径--><fileNamePattern>logs/logbackError.%d.log</fileNamePattern></rollingPolicy></appender><root level="info"><appender-ref ref="consoleLog"/><appender-ref ref="fileInfoLog"/><appender-ref ref="fileErrorLog"/></root></configuration>
3. 配置yml(日志输出级别)
logging:level:com.example: infopattern:console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
③:配置定时任务
1. 引入依赖
<!-- Quartz定时任务库-->
<dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId><version>2.3.2</version> <!-- 使用适当的版本号 -->
</dependency>
2. 创建定时任务执行逻辑类
@Slf4j
@Component
public class MyJob {@Autowiredprivate LogMapper logMapper;@Scheduled (cron = "0/10 * * * * ?") // 每隔10秒执行一次public void execute() {// 获取当前时间LocalDateTime currentTime = LocalDateTime.now();// 创建日期时间格式化对象DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");// 格式化当前时间String formattedTime = currentTime.format(formatter);log.info("定时任务执行了!" + formattedTime);LogEntity logEntity = new LogEntity();Date date = new Date();int i = logMapper.add(date);if (i > 0){log.info("插入数据成功");}else {log.error("插入数据失败");}}
}
3. 开启定时任务
在启动类上添加 @EnableScheduling 注解 必要时添加 @ComponentScan 注释
@SpringBootApplication
@EnableScheduling
@ComponentScan("com.sanss.djyp.*")
public class DjypApplication {public static void main(String[] args) {SpringApplication.run(DjypApplication.class, args);}
}
④:启动项目测试
测试成功(每隔10秒都会添加一条数据)
⑤:配置stater启动器(方法一)
作用:打成jar后在引入的新的项目中会自动执行
1.引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
2. 配置类进行注册
在
resources
文件夹下面新建一个META-INF
文件,并在下面创建spring.factories
文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.sanss.djyp.job.MyJob
⑥:配置stater启动器(方法二)推荐
直接在启动类上添加 @Configuration 注解即可
二、 打成jar包(上传到私服中)
1.配置pom.xml插件
<!-- 上传源码 -->
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-source-plugin</artifactId><version>3.0.1</version><configuration><attach>true</attach></configuration><executions><execution><phase>compile</phase><goals><goal>jar</goal></goals></execution></executions>
</plugin>
2.去掉springboot打包插件(否则会报错)
在springboot打包插件中添加一行
<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><skip>true</skip><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration>
</plugin>
3.拓展(不去掉springboot打包插件)
发现依赖的jar包结构是这样的,多了BOOT-INF/classes
因此/META-INF/spring.factories这个文件里的配置就匹配不到,所以报错了
4. 指定部署目标(上传到那个私服中)
注意事项 报错:transfer failed for <http://localhost:8081/repository/maven-releases/com/sanss/djyp/0.0.1-SNAPSHOT/djyp-0.0.1-20230601.013826-1.jar>, status: 400 Repository version policy: RELEASE does not allow version: 0.0.1-20230601.013826-1
这个错误提示表明你的仓库版本策略不允许使用 -SNAPSHOT
版本的发布。默认情况下,Maven的 maven-releases
仓库版本策略是 RELEASE
,它只允许发布稳定的、非快照版本。
要解决此问题,有两个可能的方法:
-
更新版本号:修改你的项目的版本号,移除
-SNAPSHOT
后重新构建并发布。例如,将版本号从0.0.1-SNAPSHOT
修改为0.0.1
,然后重新执行构建和发布操作。 -
使用快照仓库:如果你想继续使用快照版本进行开发和测试,你可以配置一个专门用于快照版本的仓库。在你的
settings.xml
文件中,添加一个<repository>
元素,指定一个maven-snapshots
仓库,并配置正确的URL和认证信息。<repository><id>maven-snapshots</id><url>http://localhost:8081/repository/maven-snapshots/</url><snapshots><enabled>true</enabled></snapshots> </repository>
并在你的项目中使用
maven-snapshots
仓库进行发布。
请注意,如果你选择第二种方法使用快照仓库,确保你的私有仓库正确配置了对应的 maven-snapshots
仓库,并允许使用快照版本。此外,快照版本应该仅用于开发和测试,不应该在生产环境中使用。
准备发布
<!-- 指定部署目标-->
<distributionManagement><repository><id>maven-releases</id><url>http://localhost:8081/repository/maven-releases/</url></repository>
</distributionManagement>
4. 在maven的settings.xml中添加认证信息
<server><id>maven-releases</id><!--nexus的认证id(仓库名称)--> <username>admin</username><!--nexus中的用户名密码--> <password>admin123</password> </server>
5. 运行 deploy指令 将jar包发布到私有仓库中
三、在新项目中引入jar包并自动执行
①:引入发布的jar包依赖
<dependency><groupId>com.sanss</groupId><artifactId>djyp</artifactId><version>0.0.1</version>
</dependency>
②:启动项目测试
成功