李志涛2019024002

导航

 

一、整合jdbc

1、创建一个springInitializr项目

   勾选 web————springweb、SQL————JDBC API,MYSQL Diver

2、连接数据库

3、创建yml

 

 4、在

Springboot04DataApplication同级下创建controller包,再创建JDBCController类

 

 5、启动

Springboot04DataApplication

二:整合Druid数据源
1、在pom.xml中加入相关依赖
<!--Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>

<!--log4j-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>

2、yml配置
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMills: 60000
minEvictableIdleTimeMidds: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true

#配置监控统计拦截好的filters,stat:监控统计、Log4j:日志记录、wall:防御sql注入
#如果允许时保报错 java.lang.ClassNotFountException: org.apache.log4j.Priority
#则导入log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.solwSqlMillis=500

 

 

3、在Springboot04DataApplication同级下创建config包创建DuridConfig类

@Configuration
public class DruidConfig {

@ConfigurationProperties(prefix ="spring.datasource")
@Bean
public DataSource DruidDataSource(){
return new DruidDataSource();
}

//后台监控
//因为SpringBoot 内置了 servlet容器,所以没有web.xml,替代方法:ServletRegistrationBean
@Bean
public ServletRegistrationBean StatViewServlet(){
ServletRegistrationBean<StatViewServlet> bean= new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

//后台需要有人登陆,账号密码配置
HashMap<String,String> initParameters=new HashMap<>();

//增加配置
initParameters.put("loginUsername","admin"); //登陆key 是固定的 loginUsername loginPassword
initParameters.put("loginPassword","123456");

//允许谁可以访问
initParameters.put("allow","");

//禁止谁能访问
//initParameters.put("","")

bean.setInitParameters(initParameters); //设置初始化参数
return bean;
}

//filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean=new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤那些请求呢?
Map<String,String> initParameters=new HashMap<>();

//这些东西不进行统计
initParameters.put("exclusions","*.js,**.css,/druid/*");

bean.setInitParameters(initParameters);
return bean;
}
}

4、运行Springboot04DataApplication

 

       

posted on 2021-09-29 20:37  李志涛2019024002  阅读(70)  评论(0编辑  收藏  举报