SpringBoot整合阿里Druid数据源及Spring-Data-Jpa

时间:2024-09-21 09:06:26

SpringBoot整合阿里Druid数据源及Spring-Data-Jpa

https://mp.weixin.qq.com/s?__biz=MzU0MDEwMjgwNA==&mid=2247484669&idx=1&sn=f28a9ae8067af39c8d9406b7842c7751&chksm=fb3f1d06cc489410bc5bc5ad1a857bc239962539bd51a239f406644055ef7fcbdc7975288899&scene=0&key=f90f52b171784d83da3e317c903ae4bebd202ad3353a3030ce03cbe404e2527b0b1d0761a9029f0eee109af1a66f4d9f15384196a9686dca43c689473de1369b24c20156685eedd7f09328bbcc55459c&ascene=1&uin=MjgwMTEwNDQxNg%3D%3D&devicetype=Windows-QQBrowser&version=6103000b&lang=zh_CN&pass_ticket=Pbtuc%2B57vDHGrUKlz7gN6m3DE%2BsmcWebe008LyFC7dD5%2B8zGrdL8USzjdzIexKLI

最近开辟了一个新项目,因为初期考虑到可能会调整数据库的风险,所以orm,在设计之初就考虑为Spring Data Jpa, 以下是工程data层数据,整体是参照配置多数据源的方案,进行配置的

目录

  • 因为阿里数据源 Druid

  • 整合数据源及其他事务配置

  • pom依赖

整合事务

  1. @EnableAutoConfiguration

  2. @SpringBootApplication

  3. @EnableTransactionManagement

  4. @ComponentScan(basePackages = {"com.inn.developer"})

  5. public class CodeApplication {

  6.    public static void main(String[] args) {

  7.        new SpringApplicationBuilder().web(true).sources(CodeApplication.class).run(args);

  8.    }

  9. }

创建 DruidProperties配置

  1. @Data

  2. @AllArgsConstructor

  3. @NoArgsConstructor

  4. @ConfigurationProperties(prefix = "druid")

  5. public class DruidProperties {

  6. ...

数据库参数可以参考:

参数 默认值 解释
initialSize 3 初始化配置
minIdle 3 最小连接数
maxActive 15 最大连接数
maxWait 5000 获取连接超时时间(单位:ms)
timeBetweenEvictionRunsMillis 90000 连接有效性检测时间(单位:ms)
testOnBorrow false 获取连接检测
testOnReturn false 归还连接检测
minEvictableIdleTimeMillis 1800000 最大空闲时间(单位ms)
testWhileIdle true 在获取连接后,确定是否要进行连接空间时间的检查
     
  • 配置说明:

   
     
1:minEvictableIdleTimeMillis(最大空闲时间):默认为30分钟,配置里面不进行设置。    

2:testOnBorrow ,testOnReturn 默认为关闭,可以设置为不配置。

3:testWhileIdle(在获取连接后,确定是否要进行连接空闲时间的检查)。默认为true。配置里面不再进行设置。

  • 流程说明:

    1:在第一次调用connection的时候,才会进行 initialSize的初始化。

    2:心跳检测时间线程,会休眠timeBetweenEvictionRunsMillis时间,然后只对(没有borrow的线程 减去 minIdle)的线程进行检查,如果空闲时间大于minEvictableIdleTimeMillis则进行close。

    3:testWhileIdle必须设置为true,在获取到连接后,先检查testOnBorrow,然后再判定testwhileIdle,如果连接空闲时间大于timeBetweenEvictionRunsMillis,则会进行心跳检测。

    4:不需要配置validationQuery,如果不配置的情况下会走ping命令,性能更高。

    5:连接保存在数组里面,获取连接的时候,获取数组的最后一位。在imeBetweenEvictionRunsMillis时是从前往后进行检查连接的有效性。

配置数据源及hibernate适配

数据源对象创建还是和之前一样, 笔者不太喜欢xml的方式,所以还是采用配置类

DruidAutoJpaConfiguration

  1. @Configuration

  2. @EnableConfigurationProperties(DruidProperties.class)//开启属性注入,通过@autowired注入

  3. @ConditionalOnClass(DruidDataSource.class)//表示对应的类在classpath目录下存在时,才会去解析对应的配置文件

  4. @ConditionalOnProperty(prefix = "druid", name = "url")

  5. @EnableJpaRepositories(basePackages = "com.inn.developer.model.dao",transactionManagerRef = "jpaTransactionManager", entityManagerFactoryRef = "localContainerEntityManagerFactoryBean")

  6. public class DruidAutoJpaConfiguration {

  7.    @Autowired

  8.    private DruidProperties properties;

  9.    @Bean(name = "druidDataSource")

  10.    @Primary

  11.    public DataSource dataSource() {

  12.        DruidDataSource dataSource = new DruidDataSource();

  13.        dataSource.setUrl(properties.getUrl());

  14.        dataSource.setUsername(properties.getUsername());

  15.        dataSource.setPassword(properties.getPassword());

  16.        dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());

  17.        if (properties.getInitialSize() > 0) {

  18.            dataSource.setInitialSize(properties.getInitialSize());

  19.        }

  20.        if (properties.getMinIdle() > 0) {

  21.            dataSource.setMinIdle(properties.getMinIdle());

  22.        }

  23.        if (properties.getMaxActive() > 0) {

  24.            dataSource.setMaxActive(properties.getMaxActive());

  25.        }

  26.        dataSource.setTestOnBorrow(properties.isTestOnBorrow());

  27.        dataSource.setValidationQuery("select version()");

  28.        try {

  29.            dataSource.init();

  30.        } catch (SQLException e) {

  31.            throw new RuntimeException(e);

  32.        }

  33.        return dataSource;

  34.    }

  35.    /**

  36.     * hibernate 适配器,定制方言为mysql,并打印sql

  37.     *

  38.     * @return

  39.     */

  40.    @Bean(name = "hibernateJpaVendorAdapter")

  41.    @Primary

  42.    public HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {

  43.        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();

  44.        hibernateJpaVendorAdapter.setShowSql(true);

  45.        hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");

  46.        return hibernateJpaVendorAdapter;

  47.    }

  48.    @Bean(name = "localContainerEntityManagerFactoryBean")

  49.    @Primary

  50.    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(@Qualifier("druidDataSource") DataSource dataSource

  51.            ,@Qualifier("hibernateJpaVendorAdapter") HibernateJpaVendorAdapter hibernateJpaVendorAdapter) {

  52.        LocalContainerEntityManagerFactoryBean local = new LocalContainerEntityManagerFactoryBean();

  53.        local.setDataSource(dataSource);

  54.        local.setJpaVendorAdapter(hibernateJpaVendorAdapter);

  55.        local.setPackagesToScan("com.inn.developer.model.domain");

  56.        Properties properties = new Properties();

  57.        properties.put("hibernate.format_sql", true);

  58.        properties.put("hibernate.hbm2ddl.auto", "update");

  59.        local.setJpaProperties(properties);

  60.        return local;

  61.    }

  62.    @Bean(name = "jpaTransactionManager")

  63.    @Primary

  64.    public JpaTransactionManager jpaTransactionManager(@Qualifier("localContainerEntityManagerFactoryBean") LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {

  65.        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();

  66.        EntityManagerFactory object = entityManagerFactoryBean.getObject();

  67.        jpaTransactionManager.setEntityManagerFactory(object);

  68.        return jpaTransactionManager;

  69.    }

pom依赖

  1. <dependency>

  2.            <groupId>mysql</groupId>

  3.            <artifactId>mysql-connector-java</artifactId>

  4.        </dependency>

  5.        <dependency>

  6.            <groupId>org.springframework.boot</groupId>

  7.            <artifactId>spring-boot-starter-data-jpa</artifactId>

  8.        </dependency>

  9.         <dependency>

  10.            <groupId>org.projectlombok</groupId>

  11.            <artifactId>lombok</artifactId>

  12.            <version>1.16.6</version>

  13.            <scope>provided</scope>

  14.        </dependency>

  15.          <dependency>

  16.            <groupId>com.alibaba</groupId>

  17.            <artifactId>druid</artifactId>

  18.            <version>1.0.11</version>

  19.        </dependency>

  20.         <!--依赖Spring 4.3.6之core、context、aop、beans、tx、orm和spring data commons -->

  21.        <dependency>

  22.            <groupId>org.springframework.data</groupId>

  23.            <artifactId>spring-data-jpa</artifactId>

  24.            <version>1.11.3.RELEASE</version>

  25.        </dependency>

  26.        <!--hibernate 实现JPA的框架 -->

  27.        <dependency>

  28.            <groupId>org.hibernate</groupId>

  29.            <artifactId>hibernate-entitymanager</artifactId>

  30.            <version>5.2.5.Final</version>

  31.        </dependency>

  32.        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->

  33.        <dependency>

  34.            <groupId>org.hibernate</groupId>

  35.            <artifactId>hibernate-core</artifactId>

  36.            <version>5.2.11.Final</version>

  37.        </dependency>

  38.        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-annotations -->

  39.        <dependency>

  40.            <groupId>org.hibernate</groupId>

  41.            <artifactId>hibernate-annotations</artifactId>

  42.            <version>3.5.6-Final</version>

  43.        </dependency>

招人:数心,造化心数奇;用心等你...

上一篇:webflux 与swagger2.x