相关的jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
yml配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/aw?useUicode=true&SSL=false&characterEncoding=utf-8&serverTimeone=UTC
测试类
要记住springboot默认使用的是HikariDataSource 他的速度相对块。
这里使用的是jdbcTemplate模板,也可以用dataSource调用原生的连接。
@RestController
public class SpringData {
@Autowired
private DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("/t1")
List<Map<String, Object>> test1() {
//spring默认使用的数据库是HikariDataSource
System.out.println(dataSource.getClass());
//使用jdbc来进行操作数据库 凡是看到Template的就直接拿来用这样的是封装好的
List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from student");
return mapList ;
}
}
Durid
Druid提供了性能卓越的连接池功能外,还集成了SQL监控,黑名单拦截功能。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
yml
使用type指定数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/aw?useUicode=true&SSL=false&characterEncoding=utf-8&serverTimeone=UTC
type: com.alibaba.druid.pool.DruidDataSource
druid:
filters: stat
#最大连接池数量
max-active: 200
#初始化时建立物理连接的个数
initial-size: 10
#获取连接时最大等待时间,单位毫秒
max-wait: 60000
#最小连接池数量
min-idle: 10
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: select 1
#validation-query: select 1 from dual
test-while-idle: true
test-on-borrow: false
test-on-return: false
#是否缓存preparedStatement
pool-prepared-statements: true
#要启用PSCache,必须配置大于0
max-open-prepared-statements: 200
break-after-acquire-failure: true
time-between-connect-error-millis: 300000
开启监控
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
DataSource test1(){
return new DruidDataSource();
}
//后台监控:其实就是web.xml, 因为springboot内置servlet容器所以用ServletRegistrationBean替代
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
//设置帐号密码
HashMap<String, String> hashMap = new HashMap<>();
//添加配置 key是固定的loginUsername loginPassword
hashMap.put("loginUsername","admin");
hashMap.put("loginPassword","admin");
//允许访问
hashMap.put("allow","");
//禁止访问 但是这种并不常用
// hashMap.put("名字","相应的ip");
registrationBean.setInitParameters(hashMap);
return registrationBean;
}
}