1. 引入依赖
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jdbcartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.26version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.3.0version>
dependency>
2. 配置yaml
server:
port: 19000 # ????????
spring:
application:
name: djyp-stater # ???????
datasource:
url: jdbc:mysql://ip地址:3306/djyp?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 密码
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;
}
@Override
public 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);
}
@Override
public 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);
}
1. 引入依赖 配置yml
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
dependency>
logging:
level:
com.example: info
pattern:
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> {
@Override
protected 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)
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<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%npattern>
encoder>
appender>
<appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUGlevel>
<onMatch>DENYonMatch>
<onMismatch>ACCEPTonMismatch>
filter>
<encoder>
<pattern> %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%npattern>
encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/logbackInfo.%d.logfileNamePattern>
rollingPolicy>
appender>
<appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUGlevel>
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.logfileNamePattern>
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: info
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
1. 引入依赖
<dependency>
<groupId>org.quartz-schedulergroupId>
<artifactId>quartzartifactId>
<version>2.3.2version>
dependency>
2. 创建定时任务执行逻辑类
@Slf4j
@Component
public class MyJob {
@Autowired
private 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秒都会添加一条数据)
作用:打成jar后在引入的新的项目中会自动执行
1.引入依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-autoconfigureartifactId>
dependency>
2. 配置类进行注册
在
resources
文件夹下面新建一个META-INF
文件,并在下面创建spring.factories
文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.sanss.djyp.job.MyJob
直接在启动类上添加 @Configuration 注解即可
1.配置pom.xml插件
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-source-pluginartifactId>
<version>3.0.1version>
<configuration>
<attach>trueattach>
configuration>
<executions>
<execution>
<phase>compilephase>
<goals>
<goal>jargoal>
goals>
execution>
executions>
plugin>
2.去掉springboot打包插件(否则会报错)
在springboot打包插件中添加一行
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<skip>trueskip>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
3.拓展(不去掉springboot打包插件)
4. 指定部署目标(上传到那个私服中)
注意事项 报错:transfer failed for
这个错误提示表明你的仓库版本策略不允许使用 -SNAPSHOT
版本的发布。默认情况下,Maven的 maven-releases
仓库版本策略是 RELEASE
,它只允许发布稳定的、非快照版本。
要解决此问题,有两个可能的方法:
更新版本号:修改你的项目的版本号,移除 -SNAPSHOT
后重新构建并发布。例如,将版本号从 0.0.1-SNAPSHOT
修改为 0.0.1
,然后重新执行构建和发布操作。
使用快照仓库:如果你想继续使用快照版本进行开发和测试,你可以配置一个专门用于快照版本的仓库。在你的 settings.xml
文件中,添加一个
元素,指定一个 maven-snapshots
仓库,并配置正确的URL和认证信息。
<repository>
<id>maven-snapshotsid>
<url>http://localhost:8081/repository/maven-snapshots/url>
<snapshots>
<enabled>trueenabled>
snapshots>
repository>
并在你的项目中使用 maven-snapshots
仓库进行发布。
请注意,如果你选择第二种方法使用快照仓库,确保你的私有仓库正确配置了对应的 maven-snapshots
仓库,并允许使用快照版本。此外,快照版本应该仅用于开发和测试,不应该在生产环境中使用。
准备发布
<distributionManagement>
<repository>
<id>maven-releasesid>
<url>http://localhost:8081/repository/maven-releases/url>
repository>
distributionManagement>
4. 在maven的settings.xml中添加认证信息
<server>
<id>maven-releasesid>
<username>adminusername>
<password>admin123password>
server>
5. 运行 deploy指令 将jar包发布到私有仓库中
<dependency>
<groupId>com.sanssgroupId>
<artifactId>djypartifactId>
<version>0.0.1version>
dependency>
成功