然后实际在开发的时候,我们很少用到这个数据源,比如我们用c3p0,或者开发常用的druid,这是我们阿里的数据源产品,
虽然Hikarui的性能比druid要好一点,由于druid有安全监控的整个解决方案,所以我们后来开发中用到他也非常多,那我们
接下来就整合duid数据源,我们不用他默认的
首先我们要引入druid数据源,我们从maven仓库里找到他的坐标,
https://mvnrepository.com/search?q=druid
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
我们先引入我们自定义的数据源,引入druid数据源,可以用type来指定数据源的类型,
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
我们指定成他,这样数据源就切换过来了,我们看数据源能不能切成druid的呢,我们来运行,我们来看一下,
数据源已经变了,class com.alibaba.druid.pool.DruidDataSource
#debug=true
#server.port=8081
#server.context-path=/boot02
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
logging.level.com.learn=trace
#logging.file=D:/springboot.log
logging.file=springboot.log
#logging.path=/spring/log
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd} ==== [%thread] %-5level ==== %logger{50} ==== %msg%n
#spring.resources.static-locations=classpath:/hello,classpath:/learn
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/day20
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
package com.learn.springboot;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* SpringBoot单元测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDataJDBCApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
// org.apache.tomcat.jdbc.pool.DataSource
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
但是数据源会有很多的属性设置,比如druid,初始化连接池大小,等等配置,那我们配置在哪呢,那么多的属性我就不
一个一个写了,initialSize是初始化大小,我们在DataSourceProperties里边,并没有相关的属性,所以我们后边设置的
这些,并不能绑定到数据库的配置里边,那这写配置默认是不起作用的,我们自己来写一个DruidConfig,专门来配我们的
druid,它是一个@Configuration,我们来创建一个数据源,并且加载容器中,但是我们要将属性绑定上,之前默认是绑定不上的,
我们只需要用一个熟悉的注解,我们把以"spring.datasource"为前缀的绑定进来,那我再来debug测试,
#连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
package com.learn.config;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
}
package com.learn.springboot;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* SpringBoot单元测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDataJDBCApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
// org.apache.tomcat.jdbc.pool.DataSource
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
这样我们的属性就用上了,接下来我们来配置监控,让他的的监控也能起到作用,这个怎么配置呢,其实与以前用过的
一样,他需要配置一个servlet,我们进入管理后台的请求,然后再来配置一个监控的filter,我们得配上两个这个东西,
我们没有web.xml,如果要注册servlet,就用ServletRegistrationBean,那么这个servlet叫什么呢,StatViewServlet,
帮我们监控管理后台的servlet,我们就来配他,我们new一个ServletRegistrationBean,然后把我们的servlet传进去,
然后还要传入一个urlMapping,我们处理druid下的所有请求,我们把servlet加入容器中,我们一般也会配置一些初始化
参数,比如这个servlet能配置这些参数
/**
* 注意:避免直接调用Druid相关对象例如DruidDataSource等,相关调用要到DruidStatManagerFacade里用反射实现
*
* @author sandzhang[sandzhangtoo@gmail.com]
*/
public class StatViewServlet extends ResourceServlet {
private final static Log LOG = LogFactory.getLog(StatViewServlet.class);
private static final long serialVersionUID = 1L;
public static final String PARAM_NAME_RESET_ENABLE = "resetEnable";
public static final String PARAM_NAME_JMX_URL = "jmxUrl";
public static final String PARAM_NAME_JMX_USERNAME = "jmxUsername";
public static final String PARAM_NAME_JMX_PASSWORD = "jmxPassword";
@SuppressWarnings("serial")
public abstract class ResourceServlet extends HttpServlet {
private final static Log LOG = LogFactory.getLog(ResourceServlet.class);
public static final String SESSION_USER_KEY = "druid-user";
public static final String PARAM_NAME_USERNAME = "loginUsername";
public static final String PARAM_NAME_PASSWORD = "loginPassword";
public static final String PARAM_NAME_ALLOW = "allow";
public static final String PARAM_NAME_DENY = "deny";
public static final String PARAM_REMOTE_ADDR = "remoteAddress";
初始化参数怎么配呢,allow不写就是默认允许所有,我来配置一个deny来拒绝,拒绝这个ip地址来访问,注册filter
需要FilterRegistrationBean,我们这个filter叫WebStatFilter,就来注册他,
/**
* 用于配置Web和Druid数据源之间的管理关联监控统计
*
* @author wenshao [szujobs@htomail.com]
* @author Zhangming Qi [qizhanming@gmail.com]
*/
public class WebStatFilter extends AbstractWebStatImpl implements Filter {
private final static Log LOG = LogFactory.getLog(WebStatFilter.class);
public final static String PARAM_NAME_PROFILE_ENABLE = "profileEnable";
public final static String PARAM_NAME_SESSION_STAT_ENABLE = "sessionStatEnable";
public final static String PARAM_NAME_SESSION_STAT_MAX_COUNT = "sessionStatMaxCount";
public static final String PARAM_NAME_EXCLUSIONS = "exclusions";
public static final String PARAM_NAME_PRINCIPAL_SESSION_NAME = "principalSessionName";
public static final String PARAM_NAME_PRINCIPAL_COOKIE_NAME = "principalCookieName";
public static final String PARAM_NAME_REAL_IP_HEADER = "realIpHeader";
我们看能不能来到druid的管理后台
localhost:8080/druid
按照我们指定的用户名和密码,还有WEB应用的数据监控,我们配了web filter,都能监控到WEB应用的相关信息,我们就来发一个请求,
localhost:8080/query
来查询数据的请求,这个数据就算是查出来了,包括来到我们的后台,还可以看到SQL监控,JDBC执行次数,执行的时间,druid就配置
成功了
package com.learn.config;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
// 配置Druid的监控
// 1.配置一个管理后台的Servlet
// 2.配置一个监控的Filter
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<String,String>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
initParams.put("allow", "");
initParams.put("deny", "192.168.15.21");
// 默认就是允许所有访问
bean.setInitParameters(initParams);
return bean;
}
// 2.配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<String,String>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}