> Java > java지도 시간 > 본문

SpringBoot가 druid를 사용하여 여러 데이터 소스를 구성하는 방법

WBOY
풀어 주다: 2023-05-14 12:19:05
앞으로
3565명이 탐색했습니다.

1. 배경

spring boot를 사용하여 데이터 소스는 postgresql과 mysql입니다.

2. 버전 소개

  • spring boot——2.5.4

  • druid—1.2 .11

  • postgresql— ;—2019

  • 3. 프로젝트 구조

    java 패키지 디렉토리
  • 리소스 디렉토리는 mapper.xml 파일을 저장하고 데이터 소스에 따라 패키지를 생성합니다.
  • 4. Maven 종속성
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- MySql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
로그인 후 복사

5. Yaml 구성 파일

server:
  port: 8081
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      web-stat-filter:
        enabled: true #是否启用StatFilter默认值true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
        session-stat-enable: true
        session-stat-max-count: 10
      stat-view-servlet:
        enabled: true #是否启用StatViewServlet默认值true
        url-pattern: /druid/*
        reset-enable: true
        login-username: admin
        login-password: admin
        allow:
 
      db1:
        username: postgres
        password: localhost
        url: jdbc:postgresql://localhost:5432/test
        driver-class-name: org.postgresql.Driver
        initial-size: 5  # 初始化大小
        min-idle: 5  # 最小
        max-active: 100  # 最大
        max-wait: 60000  # 配置获取连接等待超时的时间
        validation-query: select version()
        time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        min-evictable-idle-time-millis: 300000  # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒
        filters: config,wall,stat  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,&#39;wall&#39;用于防火墙
        # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
 
      db2:
        username: root
        password: localhost
        url: jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
        driver-class-name: com.mysql.cj.jdbc.Driver
        initial-size: 5  # 初始化大小
        min-idle: 5  # 最小
        max-active: 100  # 最大
        max-wait: 60000  # 配置获取连接等待超时的时间
        validation-query: select &#39;x&#39;
        time-between-eviction-runs-millis: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        min-evictable-idle-time-millis: 300000  # 指定一个空闲连接最少空闲多久后可被清除,单位是毫秒
        filters: config,wall,stat  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,&#39;wall&#39;用于防火墙
        # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true;config.decrypt=false
        test-while-idle: true
        test-on-borrow: true
        test-on-return: false
        # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
 
mybatis:
  mapper-locations: classpath:com/demo/mapper/*.xml
  type-aliases-package: com.demo.entity
  configuration:
    log-impl:
    mapUnderscoreToCamelCase: true
 
#showSql
logging:
  level:
    java.sql: debug
    org.apache.ibatis: debug
    com.demo.mapper: debug
  config: classpath:logback-spring.xml
로그인 후 복사

6. 데이터 소스 구성 파일

@Configuration
@MapperScan(basePackages = "com.demo.mapper.postgre.**", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DataSourceConfig1 {
    // 将这个对象放入Spring容器中
    @Bean(name = "oneDataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "oneSqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为oneDataSource的对象
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.postgre/*.xml"));
        return bean.getObject();
    }
 
    @Bean("oneSqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate oneSqlSessionTemplate(
            @Qualifier("oneSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
 
}
로그인 후 복사
@Configuration
@MapperScan(basePackages = "com.demo.mapper.mysql", sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DataSourceConfig2 {
    // 将这个对象放入Spring容器中
    @Bean(name = "twoDataSource")
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.druid.db2")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "twoSqlSessionFactory")
    // 表示这个数据源是默认数据源
    //@Primary
    // @Qualifier表示查找Spring容器中名字为oneDataSource的对象
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:com.demo.mapper.mysql/*.xml"));
        return bean.getObject();
    }
 
    @Bean("twoSqlSessionTemplate")
    // 表示这个数据源是默认数据源
    //@Primary
    public SqlSessionTemplate oneSqlSessionTemplate(
            @Qualifier("twoSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }
 
}
로그인 후 복사

7. 시작 클래스 구성SpringBoot가 druid를 사용하여 여러 데이터 소스를 구성하는 방법

핵심 사항: 제외 = {DataSourceAutoConfiguration.class}를 제거하고 com을 스캔합니다. .demo.mapper 디렉토리

@MapperScan("com.demo.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication .class, args);
    }
}
로그인 후 복사
8. Druid 관리 페이지

SpringBoot가 druid를 사용하여 여러 데이터 소스를 구성하는 방법주소 localhost://8081/druid, admin/admin

을 입력하세요.

위 내용은 SpringBoot가 druid를 사용하여 여러 데이터 소스를 구성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!