springboot整合Druid之一:com.alibaba.druid

package com.example.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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 org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Configuration
//@PropertySource(value = {"classpath:application.properties"})
//@ConfigurationProperties(prefix = "ds1.datasource")
public class DatasourceConfig {
    // 精确到 master 目录,以便跟其他数据源隔离
    static final String PACKAGE = "com.example.mybatis.entity";
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Value("${ds1.datasource.url}")
    private String url;
    @Value("${ds1.datasource.username}")
    private String username;
    @Value("${ds1.datasource.password}")
    private String password;
    @Value("${ds1.datasource.driverClassName}")
    private String driverClassName;

    @Value("${ds1.datasource.maxActive}")
    private Integer maxActive;
    @Value("${ds1.datasource.minIdle}")
    private Integer minIdle;
    @Value("${ds1.datasource.initialSize}")
    private Integer initialSize;
    @Value("${ds1.datasource.maxWait}")
    private Long maxWait;
    @Value("${ds1.datasource.timeBetweenEvictionRunsMillis}")
    private Long timeBetweenEvictionRunsMillis;
    @Value("${ds1.datasource.minEvictableIdleTimeMillis}")
    private Long minEvictableIdleTimeMillis;
    @Value("${ds1.datasource.testWhileIdle}")
    private Boolean testWhileIdle;
    @Value("${ds1.datasource.testWhileIdle}")
    private Boolean testOnBorrow;
    @Value("${ds1.datasource.testOnBorrow}")
    private Boolean testOnReturn;

    // spring-boot不是原生支持的druid连接池,
    // spring-boot不支持自动配druid连接池(即无法通过配置项直接支持相应的连接池连接池)
    @Bean(name = "dataSource") //DataSource对象被@Bean声明,为Spring容器所管理
    @Primary //@Primary表示这里定义的DataSource将覆盖其他来源的DataSource
    public DataSource dataSource() {
        //jdbc配置
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        //连接池配置
        dataSource.setMaxActive(maxActive);
        dataSource.setMinIdle(minIdle);
        dataSource.setInitialSize(initialSize);
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(maxWait);
        //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        //配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        //申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,检测连接是否有效
        dataSource.setTestWhileIdle(testWhileIdle);
        //申请连接时,检测连接是否有效
        dataSource.setTestOnBorrow(testOnBorrow);
        //归还连接时,检测连接是否有效
        dataSource.setTestOnReturn(testOnReturn);
        //测试连接是否有效的sql
        dataSource.setValidationQuery("select 1 from dual");

        //打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

        try {
             /*
            配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
            # 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
            # 监控统计用的filter:stat
            # 日志用的filter:log4j
            # 防御sql注入的filter:wall
            spring.datasource.filters=stat,log4j,wall
            */
            dataSource.setFilters("stat,wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage("com.example.mybatis.entity");
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DatasourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        //设置控制台管理url http://localhost:8080/druid/
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        //设置控制台管理用户
        initParameters.put("loginUsername", "admin");// 用户名
        initParameters.put("loginPassword", "admin");// 密码
        initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
        initParameters.put("allow", ""); // IP白名单 (没有配置或者为空,则允许所有访问)
        //initParameters.put("deny", "192.168.20.38");// IP黑名单 (存在共同时,deny优先于allow)
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}
package com.example.mybatis.mapper;

import com.example.mybatis.entity.Dept;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

//@Mapper
public interface DeptMapper {

   List<Dept> getAll();
   Dept getOne(String deptno);
   void insert(Dept dept);
   void update(Dept dept);
   void delete(String deptno);
}
<?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.example.mybatis.mapper.DeptMapper">
    <resultMap id="dept" type="com.example.mybatis.entity.Dept">
        <result column="deptno" property="deptno"></result>
        <result column="dname" property="dname"></result>
        <result column="loc" property="loc"></result>
    </resultMap>
    
    <sql id="base-columns">
        deptno,dname,loc
    </sql>
    <select id="queryAllDepts" resultMap="dept">
        select deptno,dname,loc from dept
    </select>

    <select id="getAll" resultMap="dept">
        select
        <include refid="base-columns"></include>
        from dept
    </select>

    <select id="getOne" resultMap="dept" parameterType="java.lang.String">
        select
        <include refid="base-columns"></include>
        from dept
        where deptno=#{deptno}
    </select>

    <insert id="insert" parameterType="com.example.mybatis.entity.Dept">
        insert into dept (deptno,dname,loc) values (#{deptno},#{dname},#{loc})
    </insert>

    <update id="update" parameterType="com.example.mybatis.entity.Dept">
    update dept set
        <if test="dname!=null and dname!=''">dname=#{dname},</if>
        <if test="loc!=null and loc!=''">loc=#{loc},</if>
        deptno=#{deptno}
     where  deptno = #{deptno}
    </update>

    <delete id="delete" parameterType="java.lang.String">
        delete from dept where  deptno = #{deptno}
    </delete>

</mapper>
ds1.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
ds1.datasource.username=scott
ds1.datasource.password=bruce123
ds1.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
ds1.datasource.initialSize=20
ds1.datasource.minIdle=20
ds1.datasource.maxActive=200
ds1.datasource.maxWait=60000
ds1.datasource.timeBetweenEvictionRunsMillis=60000
ds1.datasource.minEvictableIdleTimeMillis=300000
ds1.datasource.testWhileIdle=true
ds1.datasource.testOnBorrow=false
ds1.datasource.testOnReturn=false
ds1.datasource.poolPreparedStatements=true
ds1.datasource.maxPoolPreparedStatementPerConnectionSize=20
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>

</configuration>

发布了152 篇原创文章 · 获赞 78 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/qiuzhi__ke/article/details/105321207