springBoot整合Druid
简介:
Druid是一个JDBC组件,它包括三部分: DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。 DruidDataSource 高效可管理的数据库连接池。
第一步:导入依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.4</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
第二步:配置application.yml
配置文件
server: port: 8081spring: datasource: password: 123456 url: jdbc:mysql://localhost:3306/jsptest?useSSL=false&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver username: root type: com.alibaba.druid.pool.DruidDataSource #druid数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入 #如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity #则导入log4j 依赖就行 filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
检查Druid数据源是否配置成功:
@SpringBootTestclass SpringbootData0302ApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() { //查看默认数据源 class com.zaxxer.hikari.HikariDataSource System.out.println(dataSource.getClass()); //获取数据库连接 try { Connection connection = dataSource.getConnection(); System.out.println(connection); //关闭 connection.close(); } catch (SQLException e) { e.printStackTrace(); } }}
第四步:设置Druid的初始化配置及参数
package com.sun.config;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;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 javax.servlet.Filter;import javax.servlet.FilterRegistration;import javax.servlet.ServletRegistration;import javax.sql.DataSource;import java.util.HashMap;import java.util.Map;@Configurationpublic class DruidConfig { @ConfigurationProperties(prefix="spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } //后台监控 @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); //后台登录设置账号密码 HashMap<String, String> initParameters = new HashMap<>(); initParameters.put("loginUsername","admin"); initParameters.put("loginPassword","123456"); //允許谁能访问 initParameters.put("allow",""); bean.setInitParameters(initParameters);//初始化参数 return bean; } //filter public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); //可以过滤那些请求? HashMap<String, String> initParameters = new HashMap<>(); //这些东西不进行统计 initParameters.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParameters); return bean; }}
第五步:写出增删查改语句进行测试:
package com.sun.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;import java.util.List;import java.util.Map;@RestControllerpublic class JDBCController { @Autowired JdbcTemplate jdbcTemplate; //查询数据库所有信息 //没有实体类,数据库中的东西怎么获取? Map @GetMapping("/userList") public List<Map<String,Object>> userList(){ String sql="select * from user"; List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql); return list_maps; } //添加用户信息 @GetMapping("/addUser") public String addUser(){ String sql="insert into jsptest.user (id,username,password) values (6,'王五','123456')"; jdbcTemplate.update(sql); return "add-ok"; } //修改 @GetMapping("/updateUser/{id}") public String updateUser(@PathVariable("id") int id){ String sql="update jsptest.user set username=?,password=? where id=" id; Object[] objects = new Object[2]; objects[0]="小明2"; objects[1]="zzzzz"; jdbcTemplate.update(sql,objects); return "update-ok"; } //删除 @GetMapping("/deleteUser/{id}") public String deleteUser(@PathVariable("id") int id){ String sql="delete from jsptest.user where id=?"; jdbcTemplate.update(sql,id); return "deleteUser-ok"; }}
访问路径完成增删改操作在Druid数据源中查看相应操作
赞 (0)