SpringBoot整合Quartz及log4j实例
SpringBoot整合Quartz及log4j实例
因为之前项目中经常会做一些定时Job的东西,所以在此记录一下,目前项目中已经使用elastic-job,这个能相对比Quartz更加简单方便一些,有助于对任务调度的触发和禁止以及任务执行时间的修改。elastic-job也是基于Quartz以及ZK的,所以在使用时,需要搭建zk环境,一般使用还是根据当下开发环境使用。一下为实例:
1、项目结构
2、所需要使用的依赖pom.xml
<project xmlns="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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>com.sto.sycdata</groupId> <artifactId>syc-data</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>sto-pay-order</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <!-- 想要配置log4j2,就要先去除logging包 --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency> <!-- https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> <exclusions> <!-- 想要配置log4j,就要先去除logging包 --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> <exclusion> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> </exclusion> </exclusions> </dependency> <!-- Oracle Driver Begin --> <dependency> <groupId>oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.1.0</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> </dependencies> <build> <finalName>syc-data</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3、配置文件
application.properties
#datasource spring.datasource.druid.one.url=jdbc:oracle:thin:@//127.0.0.1:1521/test spring.datasource.druid.one.username=root spring.datasource.druid.one.password=123456 spring.datasource.druid.one.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.druid.one.initial-size=5 spring.datasource.druid.one.max-active=10 spring.datasource.druid.one.min-idle=5 spring.datasource.druid.one.max-wait=6000 spring.datasource.druid.one.validation-query=SELECT 1 FROM DUAL spring.datasource.druid.one.test-on-borrow=true spring.datasource.druid.one.test-on-return=false spring.datasource.druid.one.test-while-idle=false spring.datasource.druid.one.remove-abandoned=true spring.datasource.druid.one.remove-abandoned-timeout=30 server.port=-1
log4j.properties
log4j.rootLogger=info, stdout, file log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %m%n log4j.appender.stdout.threshold=debug # SqlMap logging configuration... log4j.logger.com.sto.sycdata.dao=DEBUG log4j.logger.com.ibatis=DEBUG log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=ERROR log4j.logger.com.ibatis.common.jdbc.ScriptRunner=ERROR log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=ERROR log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG #DailyRollingFileAppender \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6 log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.Append=true log4j.appender.file.MaxFileSize=10MB log4j.appender.file.MaxBackupIndex=1000 log4j.appender.file.File=E:/log/log222.log log4j.appender.file.DatePattern='_'yyyy-MM-dd'.log' log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %m%n log4j.appender.file.threshold=debug
4、数据源配置代码:
package com.sto.sycdata.datasource; import javax.sql.DataSource; import org.apache.ibatis.io.VFS; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.sto.sycdata.vfs.SpringBootVFS; @Configuration @MapperScan(basePackages = DataSourceConfig.MASTERMAPPERPACKAGE, sqlSessionFactoryRef="masterSqlSessionFactory") public class DataSourceConfig { static final String MASTERMAPPERPACKAGE = "com.sto.sycdata.dao"; static final String MASTERMAPPERLOCATION = "classpath:mapper/*.xml"; static final String MASTERALIASESPACKAGE = "com.sto.sycdata.entity"; @Bean(name = "dataSourceOne") @ConfigurationProperties("spring.datasource.druid.one") @Primary public DataSource dataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "masterTransactionManager") @Primary public DataSourceTransactionManager masterTransactionManager(@Qualifier("dataSourceOne") DataSource dataSourceOne) { return new DataSourceTransactionManager(dataSourceOne); } @Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier("dataSourceOne") DataSource dataSourceOne) throws Exception { //解决myBatis下 不能嵌套jar文件的问题 VFS.addImplClass(SpringBootVFS.class); final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSourceOne); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MASTERMAPPERLOCATION)); sessionFactory.setTypeAliasesPackage(MASTERALIASESPACKAGE); return sessionFactory.getObject(); } }
5、解决myBatis下 不能嵌套jar文件的问题
package com.sto.sycdata.vfs; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.ibatis.io.VFS; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; public class SpringBootVFS extends VFS { @Override public boolean isValid() { return true; } @Override protected List<String> list(URL url, String path) throws IOException { ClassLoader cl = this.getClass().getClassLoader(); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl); Resource[] resources = resolver.getResources(path + "/**/*.class"); List<Resource> resources1 = Arrays.asList(resources); List<String> resourcePaths = new ArrayList<String>(); for (Resource resource: resources1) { resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); } return resourcePaths; } private static String preserveSubpackageName(final URI uri, final String rootPath) { final String uriStr = uri.toString(); final int start = uriStr.indexOf(rootPath); return uriStr.substring(start, uriStr.length()); } }
6、实体类:
此实体类在本示例中没有用到,只是为了让示例结构看起来完整,后期可根据自己的具体情况决定实体的使用。
package com.sto.sycdata.entity; import java.io.Serializable; public class Test implements Serializable{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
7、service接口:
package com.sto.sycdata.service; public interface TestService { int queryCount(); }
8、实现类:
package com.sto.sycdata.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sto.sycdata.dao.TestDao; import com.sto.sycdata.service.TestService; @Service public class TestServiceImpl implements TestService { @Autowired private TestDao testDao; @Override public int queryCount() { return testDao.queryCount(); } }
9、dao接口:
package com.sto.sycdata.dao; public interface TestDao { int queryCount(); }
10、mapper文件TestDao.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.sto.sycdata.dao.TestDao"> <select id="queryCount" resultType="java.lang.Integer"> <![CDATA[ select count(1) from dual ]]> </select> </mapper>
11、需要定时执行的任务调度实例:
package com.sto.sycdata.schedula; import com.sto.sycdata.service.TestService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @SuppressWarnings("all") public class TestTask { private static Logger logger = Logger.getLogger(TestTask.class); @Autowired private TestService testService; public void run(){ logger.info("定时任务开始执行"); int i = testService.queryCount(); System.out.println("*************************"+ i); logger.info("定时任务执行结束"); } }
12、Quartz核心配置类:
package com.sto.sycdata.config; import com.sto.sycdata.schedula.TestTask; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @Configuration public class ScheduledConfiguration { @Bean(name = "testTaskFactoryBean") public MethodInvokingJobDetailFactoryBean payOrderPushFactoryBean(TestTask testTask) { MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean(); bean.setTargetObject(testTask); bean.setTargetMethod("run"); bean.setConcurrent(false); return bean; } @Bean(name = "testTaskPushTrigger") public CronTriggerFactoryBean payOrderPushTrigger(@Qualifier("testTaskFactoryBean") MethodInvokingJobDetailFactoryBean testTaskPushFactoryBean) { CronTriggerFactoryBean trigger = new CronTriggerFactoryBean(); trigger.setJobDetail(testTaskPushFactoryBean.getObject()); trigger.setCronExpression("0/3 * * * * ?"); return trigger; } @Bean public SchedulerFactoryBean payOrderschedulerFactoryBean(@Qualifier("testTaskPushTrigger") CronTriggerFactoryBean testTaskPushTrigger) { SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setTriggers(testTaskPushTrigger.getObject()); return schedulerFactoryBean; } }
13、测试验证: