欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Springboot—数据访问

时间:2023-07-10

目录

SQL:

自动配置分析:

  DataSourceAutoConfiguration:数据源的自动配置

JdbcTemplateAutoConfiguration:

Druid数据源:

DruidDataSourceAutoConfigure

然后我们看下关键的DruidStatProperties:

DruidDataSourceAutoConfigure:

 yml全部:

自定义实现监控页与监控功能:


SQL:

   1.首先导入JDBC场景:

org.springframework.boot spring-boot-starter-data-jdbc

2.然后我们导入驱动(数据库版本尽量与驱动版本保持一致):

mysql mysql-connector-java 5.1.49

自动配置分析:

  DataSourceAutoConfiguration:数据源的自动配置

@EnableConfigurationProperties({DataSourceProperties.class})@import({DataSourcePoolmetadataProvidersConfiguration.class, DataSourceInitializationConfiguration.class})public class DataSourceAutoConfiguration { public DataSourceAutoConfiguration() { }

  可以发现底层默认配置好的连接池为:HikariDataSource

@Configuration(proxyBeanMethods = false)@Conditional(PooledDataSourceCondition.class)@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })@import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })protected static class PooledDataSourceConfiguration

然后我们看看被数据源自动配置所绑定的DataSourceProperties:

@ConfigurationProperties( prefix = "spring.datasource")public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean { private ClassLoader classLoader; private boolean generateUniqueName = true; private String name; private Class<? extends DataSource> type; private String driverClassName; private String url; private String username; private String password; private String jndiName;

所以说我们可以用yml对数据源驱动进行配置(以spring.datasource.xxx进行配置)

spring: datasource: url: jdbc:mysql://localhost:3306/db_account username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver

JdbcTemplateAutoConfiguration:

  JdbcTemplate的自动配置,里面有对数据库的crud;

@Configuration( proxyBeanMethods = false)@ConditionalOnClass({DataSource.class, JdbcTemplate.class})@ConditionalOnSingleCandidate(DataSource.class)@AutoConfigureAfter({DataSourceAutoConfiguration.class})@EnableConfigurationProperties({JdbcProperties.class})@import({JdbcTemplateConfiguration.class, NamedParameterJdbcTemplateConfiguration.class})public class JdbcTemplateAutoConfiguration { public JdbcTemplateAutoConfiguration() { }}

JdbcProperties中绑定了jdbc操作(以spring.jdbc.xxx在yml中配置):

@ConfigurationProperties( prefix = "spring.jdbc")public class JdbcProperties { private final JdbcProperties.Template template = new JdbcProperties.Template(); public JdbcProperties() { }

扩:

DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud

可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc") 来修改JdbcTemplate@Bean@Primary JdbcTemplate;容器中有这个组件JndiDataSourceAutoConfiguration: jndi的自动配置XADataSourceAutoConfiguration: 分布式事务相关的

测试:

@Slf4j@SpringBootTestclass Boot05WebAdminApplicationTests { @Autowired JdbcTemplate jdbcTemplate; @Test void contextLoads() {// jdbcTemplate.queryForObject("select * from account_tbl")// jdbcTemplate.queryForList("select * from account_tbl",) Long aLong = jdbcTemplate.queryForObject("select count(*) from account_tbl", Long.class); log.info("记录总数:{}",aLong); }}

Druid数据源:

  这里放上druid的文档

https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98English https://github.com/alibaba/druid/wiki/FAQ

  在springboot中,我们不能像之前那样导入bean来配置数据源,或者在web.xml中通过servlet映射来配置功能了;

而是自定义Configuration,注册组件的方式或者通过yaml配置的方式来配置数据源增加配置功能;

DruidDataSourceAutoConfigure

 可以发现它是要在DataSourceAutoConfiguration之前执行的,因为DataSourceAutoConfiguration里面配置了默认数据源,所以要先执行;

@Configuration@ConditionalOnClass({DruidDataSource.class})@AutoConfigureBefore({DataSourceAutoConfiguration.class})@EnableConfigurationProperties({DruidStatProperties.class, DataSourceProperties.class})@import({DruidSpringAopConfiguration.class, DruidStatViewServletConfiguration.class, DruidWebStatFilterConfiguration.class, DruidFilterConfiguration.class})public class DruidDataSourceAutoConfigure { private static final Logger LOGGER = LoggerFactory.getLogger(DruidDataSourceAutoConfigure.class); public DruidDataSourceAutoConfigure() { } @Bean( initMethod = "init" ) @ConditionalOnMissingBean public DataSource dataSource() { LOGGER.info("Init DruidDataSource"); return new DruidDataSourceWrapper(); }}

然后我们看下关键的DruidStatProperties:

里面能够配置的东西有很多:以spring.datasource.druid为前缀,实现aoppatterns(监控springBean);还可以开启filters:stat,wall,slf4j等功能(全局性的,不是具体的)

大致有两个功能:1:StatViewServlet:配置监控页功能;2:WebStatFilter:监控web

@ConfigurationProperties("spring.datasource.druid")public class DruidStatProperties { private String[] aopPatterns; private DruidStatProperties.StatViewServlet statViewServlet = new DruidStatProperties.StatViewServlet(); private DruidStatProperties.WebStatFilter webStatFilter = new DruidStatProperties.WebStatFilter(); public DruidStatProperties() { } public String[] getAopPatterns() { return this.aopPatterns; } public void setAopPatterns(String[] aopPatterns) { this.aopPatterns = aopPatterns; } public DruidStatProperties.StatViewServlet getStatViewServlet() { return this.statViewServlet; } public void setStatViewServlet(DruidStatProperties.StatViewServlet statViewServlet) { this.statViewServlet = statViewServlet; } public DruidStatProperties.WebStatFilter getWebStatFilter() { return this.webStatFilter; } public void setWebStatFilter(DruidStatProperties.WebStatFilter webStatFilter) { this.webStatFilter = webStatFilter; } public static class WebStatFilter { private boolean enabled; private String urlPattern; private String exclusions; private String sessionStatMaxCount; private String sessionStatEnable; private String principalSessionName; private String principalcookieName; private String profileEnable;} public static class StatViewServlet { private boolean enabled; private String urlPattern; private String allow; private String deny; private String loginUsername; private String loginPassword; private String resetEnable;}

 在yml中实现对statviewServlet与webstatFilter的全局配置:

spring: datasource: url: jdbc:mysql://localhost:3306/db_account username: Wuyuhang password: 2002514wyh11 driver-class-name: com.mysql.jdbc.Driver druid: filters: stat,wall,slf4j #开启监控和防火墙and日志功能 stat-view-servlet: admin login-password: 123456 reset-enable: false#监控web应用 web-stat-filter: enabled: true url-pattern: @Bean public ServletRegistrationBean statViewServlet(){// statViewServlet就是监控视图响应 StatViewServlet statViewServlet = new StatViewServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid @Bean public FilterRegistrationBean webStatFilter(){ WebStatFilter webStatFilter = new WebStatFilter(); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter); filterRegistrationBean.setUrlPatterns(Arrays.asList("/*")); filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; }

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。