赞
踩
目录
4、自定义DruidDataSource 组件,配置 Druid 数据源监控
5、配置 Druid web 监控 filter 过滤器
5、在resources目下创建对应的UserMapper.xml
8、目前使用的是Druid数据库连接池,自定义DruidConfig
- spring:
- datasource:
- username: root
- password: luolin123
- url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
- driver-class-name: com.mysql.jdbc.Driver
1、有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据,有了连接,就可以使用原生的 JDBC 语句来操作数据库;
2、即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate 。
3、数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。
4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用
5、JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的JdbcTemplateConfiguration 类
JdbcTemplate主要提供以下几类方法:
execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句; batchUpdate方法用于执行批处理相关语句;
query方法及queryForXXX方法:用于执行查询相关语句;
call方法:用于执行存储过程、函数相关语句。、
- package com.rk.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;
-
- @RestController//返回字符串,不走视图解析器
- public class JDBCController {
-
- @Autowired
- JdbcTemplate jdbcTemplate;
-
- //查询user表中所有数据返回到前端页面
- @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 user(id,name,pwd) values (4,'王敏','123456')";
- jdbcTemplate.update(sql);
- return "add-ok";
-
- }
-
- //修改信息
- @GetMapping("/updateUser/{id}")
- public String updateUser(@PathVariable("id") int id){
- String sql="update user set name=?,pwd=? where id="+id;
- //封装参数
- Object[] objects=new Object[2];
- objects[0]="罗林";
- objects[1]="123456";
- jdbcTemplate.update(sql,objects);
- return "update-ok";
- }
-
- //删除用户
- @GetMapping("/deleteUser/{id}")
- public String deleteUser(@PathVariable("id") int id){
- String sql="delete from user where id=?";
- jdbcTemplate.update(sql,id);
- return "delete-ok";
- }
- }
-
-
1、Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
2、Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
3、Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
4、Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 JavaWeb 上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.21</version>
- </dependency>
-
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- spring:
- datasource:
- username: root
- password: luolin123
- url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
- driver-class-name: com.mysql.jdbc.Driver
- type: com.alibaba.druid.pool.DruidDataSource #指定数据源
-
-
- #Spring Boot 默认是不注入这些属性值的,需要自己绑定
- #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.Priority
- #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
- filters: stat,wall,log4j
- maxPoolPreparedStatementPerConnectionSize: 20
- useGlobalDataSourceStat: true
- connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
-
-
- package com.rk.config;
- import com.alibaba.druid.pool.DruidDataSource;
- import com.alibaba.druid.support.http.StatViewServlet;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.boot.web.servlet.ServletRegistrationBean;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import java.util.HashMap;
- import java.util.Map;
-
- @Configuration
- public class DruidConfig {
-
- @ConfigurationProperties(prefix = "spring.datasource")
- @Bean
- public DruidDataSource druidDataSource() {
- return new DruidDataSource();
- }
-
- ///配置 Druid 监控管理后台的Servlet;
- //内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
- @Bean
- public ServletRegistrationBean statViewServlet() {
- ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
- // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
- // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
- Map<String, String> initParams = new HashMap<>();
- initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
- initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
- //后台允许谁可以访问
- //initParams.put("allow", "localhost"):表示只有本机可以访问
- //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
- initParams.put("allow", "");
- //deny:Druid 后台拒绝谁访问
- //initParams.put("rk", "192.168.1.20");表示禁止此ip访问
- //设置初始化参数
- bean.setInitParameters(initParams);
- return bean;
- }
-
- }
启动: 进入druid/login.html页面(druid自动生成的)
进入之后
-
- //配置Druid监控功能
- //WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
- @Bean
- public FilterRegistrationBean webStatFilter(){
- FilterRegistrationBean bean=new FilterRegistrationBean();
- bean.setFilter(new WebStatFilter());
- //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
- Map<String, String> initParams = new HashMap<>();
- initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
- bean.setInitParameters(initParams);
- //"/*" 表示过滤所有请求
- bean.setUrlPatterns(Arrays.asList("/*"));
- return bean;
- }
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jdbc</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.1</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.21</version>
- </dependency>
-
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </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>
- <dependency>
- <groupId>org.elasticsearch</groupId>
- <artifactId>elasticsearch</artifactId>
- <version>2.4.0</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>5.3.12</version>
- </dependency>
- </dependencies>
- spring:
- datasource:
- username: root
- password: luolin123
- url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
- driver-class-name: com.mysql.jdbc.Driver
- type: com.alibaba.druid.pool.DruidDataSource #指定数据源
-
-
- #Spring Boot 默认是不注入这些属性值的,需要自己绑定
- #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.Priority
- #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
- filters: stat,wall,log4j
- maxPoolPreparedStatementPerConnectionSize: 20
- useGlobalDataSourceStat: true
- connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
-
-
- package com.rk.pojo;
- import lombok.AllArgsConstructor;
- import lombok.Data;
- import lombok.NoArgsConstructor;
- @Data
- @AllArgsConstructor
- @NoArgsConstructor
- public class User {
- private int id;
- private String name;
- private String pwd;
- }
- package com.rk.mapper;
- import com.rk.pojo.User;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Param;
- import org.springframework.stereotype.Repository;
- import java.util.List;
- @Mapper//表示这是一个mybatis的mapper类
- @Repository
- public interface UserMapper {
- List<User> queryUserList();//查询所有用户
- void deleteUser(@Param("uid") int id);//根据id删除
- void updateUser(@Param("uid") int id);//根据id修改
- void addUser(User user);//增加用户
- User queryByid(@Param("uid") int id);//通过id查询用户
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.rk.mapper.UserMapper">
- <select id="queryUserList" resultType="User">
- select * from user
- </select>
-
- <delete id="deleteUser" parameterType="int">
- delete from user where id=#{uid}
- </delete>
-
- <update id="updateUser" parameterType="int">
- update user
- set name='罗林'
- where id=#{uid}
- </update>
-
- <insert id="addUser" parameterType="User">
- insert into user (id,name, pwd)
- values (#{id},#{name},#{pwd})
- </insert>
-
- <select id="queryByid" resultType="User" parameterType="int">
- select * from user
- where id=#{uid}
- </select>
-
- </mapper>
如果直接pojo文件目录下创建mapper.xml,则需要在pom.xml的<build>中过滤资源路径
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*.xml</include>
- </includes>
- <filtering>true</filtering>
- </resource>
- </resources>
- #指定myBatis的核心配置文件与Mapper映射文件
- mybatis.mapper-locations=classpath:mapper/*.xml
- # 注意:对应实体类的路径
- mybatis.type-aliases-package=com.rk.pojo
- package com.rk.controller;
-
- import com.rk.mapper.UserMapper;
- import com.rk.pojo.User;
- import org.springframework.beans.factory.annotation.Autowired;
- 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;
-
- @RestController
- public class UserController {
-
- @Autowired
- private UserMapper userMapper;
- @GetMapping("/query")
- public List<User> query(){
- List<User> users = userMapper.queryUserList();
- return users;
- }
-
- @GetMapping("/update/{id}")
- public void updateUser(@PathVariable("id") int id){
- userMapper.updateUser(id);
- }
-
- @GetMapping("/delete/{id}")
- public void deleteUser(@PathVariable("id") int id){
- userMapper.deleteUser(id);
- }
-
- @GetMapping("/add")
- public void AddUser(){
- User user=new User();
- user.setId(4);
- user.setName("罗敏");
- user.setPwd("luolin");
- userMapper.addUser(user);
- }
-
-
- @GetMapping("/querybyid/{id}")
- public User queryUser(@PathVariable("id") int id){
- return userMapper.queryByid(id);
- }
-
- }
- package com.rk.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 java.util.Arrays;
- import java.util.HashMap;
- import java.util.Map;
- @Configuration//代表是一个spring的配置类 相当于bean.xml
- public class DruidConfig {
-
- @ConfigurationProperties(prefix = "spring.datasource")
- @Bean
- public DruidDataSource druidDataSource() {
- return new DruidDataSource();
- }
-
- ///配置 Druid 监控管理后台的Servlet;
- //内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
- @Bean
- public ServletRegistrationBean statViewServlet() {
- ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
- // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
- // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
- Map<String, String> initParams = new HashMap<>();
- initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
- initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
- //后台允许谁可以访问
- //initParams.put("allow", "localhost"):表示只有本机可以访问
- //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
- initParams.put("allow", "");
- //deny:Druid 后台拒绝谁访问
- //initParams.put("rk", "192.168.1.20");表示禁止此ip访问
- //设置初始化参数
- bean.setInitParameters(initParams);
- return bean;
- }
-
-
- //配置Druid监控功能
- //WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
- @Bean
- public FilterRegistrationBean webStatFilter(){
- FilterRegistrationBean bean=new FilterRegistrationBean();
- bean.setFilter(new WebStatFilter());
- //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
- Map<String, String> initParams = new HashMap<>();
- initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
- bean.setInitParameters(initParams);
- //"/*" 表示过滤所有请求
- bean.setUrlPatterns(Arrays.asList("/*"));
- return bean;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。