SpringBoot中使用多資料來源

2021-08-25 16:45:21 字數 2630 閱讀 9401

一、在.yml中配置資料來源:

spring:

datasource:

type: com.alibaba.druid.pool.druiddatasource

driverclassname: com.mysql.jdbc.driver

druid:

first: #資料來源1

url: jdbc:mysql://localhost:3306/renren_security?allowmultiqueries=true&useunicode=true&characterencoding=utf-8&usessl=true

username: admin

password: admin

second: #資料來源2

url: jdbc:mysql://localhost:3306/renren_security?allowmultiqueries=true&useunicode=true&characterencoding=utf-8&usessl=true

username: admin

password: admin

initial-size: 10

max-active: 100

min-idle: 10

max-wait: 60000

pool-prepared-statements: true

max-pool-prepared-statement-per-connection-size: 20

time-between-eviction-runs-millis: 60000

min-evictable-idle-time-millis: 300000

#validation-query: select 1 from dual

test-while-idle: true

test-on-borrow: false

test-on-return: false

stat-view-servlet:

enabled: true

url-pattern: /druid/*

#login-username: admin

#login-password: admin

filter:

stat:

log-slow-sql: true

slow-sql-millis: 1000

merge-sql: false

wall:

config:

multi-statement-allow: true

二、使用元註解:

/**

* 多資料來源註解

*/ @target(elementtype.method)

@retention(retentionpolicy.runtime)

@documented

public @inte***ce datasource

三、配置多資料來源名稱:

/**

* 增加多資料來源,在此配置

*/ public inte***ce datasourcenames

@override

protected object determinecurrentlookupkey()

public static void setdatasource(string datasource)

public static string getdatasource()

public static void cleardatasource() 五、配置druid多資料來源:

/**

* 配置druid多資料來源

*/ @configuration

public class dynamicdatasourceconfig

@bean

@configurationproperties("spring.datasource.druid.second")

public datasource seconddatasource()

@bean

@primary

public dynamicdatasource datasource(datasource firstdatasource, datasource seconddatasource) 六、多資料來源切面處理類:

** * 多資料來源,切面處理類

*/ @aspect

@component

public class datasourceaspect implements ordered

@around("datasourcepointcut()")

public object around(proceedingjoinpoint point) throws throwable else

try finally

}@override

public int getorder() 七、多資料來源單元測試:

@runwith(springrunner.class)

@springboottest

public class dynamicdatasourcetest

Spring Boot中使用MongoDB資料庫

前段時間分享了關於spring boot中使用redis的文章,除了redis之後,我們在網際網路產品中還經常會用到另外一款著名的nosql資料庫mongodb。下面就來簡單介紹一下mongodb,並且通過乙個例子來介紹spring boot中對mongodb訪問的配置和使用。mongodb是乙個基...

Spring Boot中使用MongoDB資料庫

前段時間分享了關於spring boot中使用redis的文章,除了redis之後,我們在網際網路產品中還經常會用到另外一款著名的nosql資料庫mongodb。下面就來簡單介紹一下mongodb,並且通過乙個例子來介紹spring boot中對mongodb訪問的配置和使用。mongodb是乙個基...

SpringBoot中使用日誌

結果 所有配置檔案都會被載入,高優先順序的配置檔案會覆蓋低優先順序的配置檔案 springboot 底層是spring框架,spring框架預設是用jcl springboot選用slf4j和logback作為日誌框架 如何使用slf4j import org.slf4j.logger import...