Spring boot 集成 Druid 數(shù)據(jù)源過程詳解
Druid是阿里開源的一個JDBC應(yīng)用組件,其中包括三部分:
- DruidDriver:代理Driver,能夠提供基于Filter-Chain模式的插件體系。
- DruidDataSource:高效可管理的數(shù)據(jù)庫連接池。
- SQLParser:實用SQL語法分析
官方文檔:https://github.com/alibaba/druid/wiki
依賴
pom.xml
Druid Spring Boot Starter是阿里官方提供的Spring Boot插件,用于在Spring Boot項目中集成Druid數(shù)據(jù)庫連接池和監(jiān)控
<!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
配置
application.yml
server: port: 8001 spring: datasource: name: druidDataSource type: com.alibaba.druid.pool.DruidDataSource druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/coisini?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: root password: sunday filters: stat,wall,log4j,config max-active: 100 initial-size: 1 max-wait: 60000 min-idle: 1 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: select 'x' test-while-idle: true test-on-borrow: false test-on-return: false pool-prepared-statements: true max-open-prepared-statements: 50 max-pool-prepared-statement-per-connection-size: 20
DruidDataSourceProperties.class
配置類對Druid進(jìn)行自定義屬性配置
@ConfigurationProperties(prefix = "spring.datasource.druid") public class DruidDataSourceProperties { // jdbc private String driverClassName; private String url; private String username; private String password; // jdbc connection pool private int initialSize; private int minIdle; private int maxActive = 100; private long maxWait; private long timeBetweenEvictionRunsMillis; private long minEvictableIdleTimeMillis; private String validationQuery; private boolean testWhileIdle; private boolean testOnBorrow; private boolean testOnReturn; private boolean poolPreparedStatements; private int maxPoolPreparedStatementPerConnectionSize; // filter private String filters; public int getInitialSize() { return initialSize; } public void setInitialSize(int initialSize) { this.initialSize = initialSize; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public long getMaxWait() { return maxWait; } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } public long getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public boolean isPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public int getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Druid Spring Starter簡化了很多配置,如果默認(rèn)配置不滿足你的需求,可以自定義配置,參考文檔:
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
配置Servlet和Filter
DruidConfig.class
@EnableConfigurationProperties:用于導(dǎo)入Druid的配置信息
@Configuration @EnableConfigurationProperties({DruidDataSourceProperties.class}) public class DruidConfig { @Autowired private DruidDataSourceProperties properties; @Bean @ConditionalOnMissingBean public DataSource druidDataSource() { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(properties.getDriverClassName()); druidDataSource.setUrl(properties.getUrl()); druidDataSource.setUsername(properties.getUsername()); druidDataSource.setPassword(properties.getPassword()); druidDataSource.setInitialSize(properties.getInitialSize()); druidDataSource.setMinIdle(properties.getMinIdle()); druidDataSource.setMaxActive(properties.getMaxActive()); druidDataSource.setMaxWait(properties.getMaxWait()); druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); druidDataSource.setValidationQuery(properties.getValidationQuery()); druidDataSource.setTestWhileIdle(properties.isTestWhileIdle()); druidDataSource.setTestOnBorrow(properties.isTestOnBorrow()); druidDataSource.setTestOnReturn(properties.isTestOnReturn()); druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements()); druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize()); try { druidDataSource.setFilters(properties.getFilters()); druidDataSource.init(); } catch (SQLException e) { e.printStackTrace(); } return druidDataSource; } /** * 注冊Servlet信息, 配置監(jiān)控視圖 * @return */ @Bean @ConditionalOnMissingBean public ServletRegistrationBean<Servlet> druidServlet() { ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*"); //白名單: // servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48"); //IP黑名單 (存在共同時,deny優(yōu)先于allow) : 如果滿足deny的話提示:Sorry, you are not permitted to view this page. servletRegistrationBean.addInitParameter("deny","192.168.1.119"); //登錄查看信息的賬號密碼, 用于登錄Druid監(jiān)控后臺 servletRegistrationBean.addInitParameter("loginUsername", "admin"); servletRegistrationBean.addInitParameter("loginPassword", "admin"); //是否能夠重置數(shù)據(jù). servletRegistrationBean.addInitParameter("resetEnable", "true"); return servletRegistrationBean; } /** * 注冊Filter信息, 監(jiān)控攔截器 * @return */ @Bean @ConditionalOnMissingBean public FilterRegistrationBean<Filter> filterRegistrationBean() { FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; } }
resources目錄下添加log4j參數(shù)配置文件
### set log levels ### log4j.rootLogger = INFO,DEBUG, console, infoFile, errorFile ,debugfile,mail LocationInfo=true log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m %x %n log4j.appender.infoFile = org.apache.log4j.DailyRollingFileAppender log4j.appender.infoFile.Threshold = INFO log4j.appender.infoFile.File = C:/logs/log log4j.appender.infoFile.DatePattern = '.'yyyy-MM-dd'.log' log4j.appender.infoFile.Append=true log4j.appender.infoFile.layout = org.apache.log4j.PatternLayout log4j.appender.infoFile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m %x %n log4j.appender.errorFile = org.apache.log4j.DailyRollingFileAppender log4j.appender.errorFile.Threshold = ERROR log4j.appender.errorFile.File = C:/logs/error log4j.appender.errorFile.DatePattern = '.'yyyy-MM-dd'.log' log4j.appender.errorFile.Append=true log4j.appender.errorFile.layout = org.apache.log4j.PatternLayout log4j.appender.errorFile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m %x %n log4j.appender.debugfile = org.apache.log4j.DailyRollingFileAppender log4j.appender.debugfile.Threshold = DEBUG log4j.appender.debugfile.File = C:/logs/debug log4j.appender.debugfile.DatePattern = '.'yyyy-MM-dd'.log' log4j.appender.debugfile.Append=true log4j.appender.debugfile.layout = org.apache.log4j.PatternLayout log4j.appender.debugfile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m %x %n
編譯運行
啟動應(yīng)用,訪問http://localhost:8001/druid/login.html,如下:
用戶名與密碼為DriudConfig中配置的登錄賬號和密碼:admin/admin
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot用@Async注解實現(xiàn)異步任務(wù)
這篇文章主要介紹了SpringBoot用@Async注解實現(xiàn)異步任務(wù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12解決微服務(wù)中關(guān)于用戶token處理到的坑
這篇文章主要介紹了解決微服務(wù)中關(guān)于用戶token處理到的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Spring中propagation的7種事務(wù)配置及說明
這篇文章主要介紹了Spring中propagation的7種事務(wù)配置及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Java遠(yuǎn)程調(diào)用Shell腳本并獲取輸出信息【推薦】
這篇文章主要介紹了Java遠(yuǎn)程調(diào)用Shell腳本并獲取輸出信息,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09Java實現(xiàn)學(xué)生信息管理系統(tǒng)(借助Array?List)
這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)學(xué)生信息管理系統(tǒng),借助Array?List,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01