springboot 创建非web项目及数据源简单使用
项目组马上要使用springboot来重构程序,首先要对几个比较小的非web项目重构,所以新手入门,简单做了个小例子
代码结构如下:
dao层
package com.mysping.myboot001.dao.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.mysping.myboot001.dao.UserDao; @Repository public class UserDaoImpl implements UserDao{ @Resource private JdbcTemplate jdbcTemplate; @Override public List<Map<String, Object>> queryForList() throws Exception { String sql = "select * from springboot.sys_user"; return this.jdbcTemplate.queryForList(sql); } @Override public DataSource getDataSource() { return this.jdbcTemplate.getDataSource(); } }
service层
package com.mysping.myboot001.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.mysping.myboot001.dao.UserDao; import com.mysping.myboot001.service.UserService; import com.zaxxer.hikari.HikariDataSource; @Service public class UserServiceImpl implements UserService{ @Resource private UserDao userDao; @Override public List<Map<String, Object>> queryForUserList() throws Exception { return userDao.queryForList(); } @Override public HikariDataSource getHikariCpDataSource() { return (HikariDataSource) userDao.getDataSource(); } }
springboot启动类
package com.mysping.myboot001; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Myboot001Application { public static void main(String[] args) { SpringApplication.run(Myboot001Application.class, args); } }
非web项目,要运行的代码需要实现CommandLineRunner或者ApplicationRunner接口,可参考官方文档:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-command-line-runner
对于分布在多个实体类中需要执行的代码,可通过实现Ordered接口,或者使用Order注解来控制,参数值越小,执行优先级越高
package com.mysping.myboot001; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.sql.DataSource; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import com.mysping.myboot001.service.UserService; import com.zaxxer.hikari.HikariDataSource; @Component public class MainBusiEntry implements CommandLineRunner{ private Logger logger = LogManager.getLogger(MainBusiEntry.class); @Resource private UserService userService; @Override public void run(String... args) throws Exception { List<Map<String, Object>> queryForUserList = userService.queryForUserList(); logger.info("queryForUserList: {}", queryForUserList); HikariDataSource hikariCpDataSource = userService.getHikariCpDataSource(); /* * idleTimeout改制在官方文档中意为:空闲连接最大存活时间,这个参数只有在maximumPoolSize的值大于minimumIdle时才生效, * 允许输入的最小值为10000ms(10秒),默认为600000(10分钟) * * 但在测试中,当配置600000,即10分钟时,getIdleTimeout打印的值为0,当配置比299000大的数字时,getIdleTimeout打印的值为0,具体情况还需调查 */ logger.info("maxPoolSize: {}, maxLifeTime: {}, conTimeout: {}, autoCommit: {}, idleTimeout: {} ", hikariCpDataSource.getMaximumPoolSize(), hikariCpDataSource.getMaxLifetime(), hikariCpDataSource.getConnectionTimeout(), hikariCpDataSource.isAutoCommit(), hikariCpDataSource.getIdleTimeout()); } }
applcaition.properties配置,本例中使用的数据源为默认的数据源HikariCP,参考文档:https://github.com/brettwooldridge/HikariCP
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://192.168.103.51:3306/springboot?characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&zeroDateTimeBehavior=convertToNull spring.datasource.username=root spring.datasource.password=12345 ## 连接池允许的最大连接数,如果包括空闲连接和正在使用的连接,当连接池连接被用完用,其他线程在获取连接时,在connectionTimeout时间之前,getConnection将一直处于阻塞状态 spring.datasource.hikari.maximum-pool-size=20 ## 空闲连接最大存活时间,这个参数只有在maximumPoolSize的值大于minimumIdle时才生效,允许输入的最小值为10000ms(10秒),默认为600000(10分钟) spring.datasource.hikari.idle-timeout=600000 ## 最小空闲连接池数量,HikariCP建议不要设置改值,将连接池的大小设置为固定大小,默认改值与maximumPoolSize大小一致 spring.datasource.hikari.minimum-idle=20 ## 等待从连接池获取连接的最大时间,单位微秒,最小值为250ms,默认值为30000(30秒) spring.datasource.hikari.connection-timeout=10000 ## 默认为true spring.datasource.hikari.auto-commit=true ## 连接池中连接的最大生命周期,默认设置为1800000(30分钟),其值也取决于idleTimeout spring.datasource.hikari.max-lifetime=300000 ## 该属性用于设置如果连接池不能正确产生初始连接时,是否迅速返回错误信息,默认为1 spring.datasource.hikari.initialization-fail-timeout=1 ## 验证连接是否有效的最大时间,该值必须小于connectionTimeout,最小值为250ms,默认为5000(5秒) spring.datasource.hikari.validation-timeout=5000
log4j2.xml
<!-- monitorInterval表示动态刷新配置的秒数,不用重启 --> <configuration debug="off" monitorInterval="1800"> <Properties> <Property name="log-path">D:/Programs/eclipseworkplace/logs/myboot001</Property> </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36}.%M()/%L - %msg%xEx%n"/> </Console> <RollingFile name="DailyRollingFile" fileName="${log-path}/cell.log" filePattern="${log-path}/cell-%d{yyyy-MM-dd}.log.gz"> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> </Policies> <DefaultRolloverStrategy> <Delete basePath="${log-path}" maxDepth="2"> <IfFileName glob="*.log.gz"/> <IfLastModified age="30d"/> </Delete> </DefaultRolloverStrategy> <PatternLayout pattern="[%p] %t %d{HH:mm:ss,SSS} %c{1}:%L(%M) %m%n"/> </RollingFile> </Appenders> <Loggers> <root level="INFO"> <appender-ref ref="DailyRollingFile"/> </root> </Loggers> </configuration>
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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> <groupId>com.mysping</groupId> <artifactId>myboot001</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>myboot001</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.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-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>