亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

spring boot多數據源動態切換代碼實例

發布時間:2020-08-22 09:42:40 來源:腳本之家 閱讀:237 作者:炫舞風中 欄目:編程語言

這篇文章主要介紹了spring boot多數據源動態切換代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

當項目中存在多數據源時,就涉及到數據源的動態切換,通過研究,特此記錄一下。

1、maven依賴

<!--數據庫連接-->
<dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.4</version>
      <scope>runtime</scope>
    </dependency>
<!--數據庫連接池->
<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.10</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
<!--aop->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

2、多數據源信息配置

#多數據源測試
spring:
 datasource:
  druid:
   master:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    username: test
    password: test
    url: jdbc:oracle:thin:@//ip1:1521/orcl
   slave:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    username: test
    password: test
    url: jdbc:oracle:thin:@//ip2:1521/orcl

3、數據源配置信息轉換成實體類

@ConfigurationProperties(prefix = "spring.datasource.druid")
@Data
@Component
public class DataSourceProperties {
  private Map<String,String>master;
  private Map<String,String>slave;
}

4、動態數據源切換類

public class DynamicDataSource extends AbstractRoutingDataSource {

  private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

  public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
    super.setDefaultTargetDataSource(defaultTargetDataSource);
    super.setTargetDataSources(targetDataSources);
    super.afterPropertiesSet();
  }


  @Override
  protected Object determineCurrentLookupKey() {
    return getDataSource();
  }

  public static void setDataSource(String dataSource) {
    contextHolder.set(dataSource);
  }

  public static String getDataSource() {
    return contextHolder.get();
  }

  public static void clearDataSource() {
    contextHolder.remove();
  }
}

5、多數據源配置類

@Configuration
public class DynamicDataSourceConfig {

  @Bean
  public DataSource master(@Autowired DataSourceProperties dataSourceProperties){
    DruidDataSource druidDataSource = new DruidDataSource();
    Map<String, String> master = dataSourceProperties.getMaster();
    druidDataSource.setUsername(master.get("username"));
    druidDataSource.setPassword(master.get("password"));
    druidDataSource.setUrl(master.get("url"));
    //其他參數配置 省略
    return druidDataSource;
  }

  @Bean
  public DataSource slave(@Autowired DataSourceProperties dataSourceProperties){
    DruidDataSource druidDataSource = new DruidDataSource();
    Map<String, String> slave = dataSourceProperties.getSlave();
    druidDataSource.setUsername(slave.get("username"));
    druidDataSource.setPassword(slave.get("password"));
    druidDataSource.setUrl(slave.get("url"));
    //其他參數配置 省略
    return druidDataSource;
  }

  @Bean
  @Primary
  public DynamicDataSource dataSource(DataSource master,DataSource slave){
    Map<Object,Object>map = new HashMap<>(4);
    map.put("master",master);
    map.put("slave",slave);
    return new DynamicDataSource(master,map);
  }
}

6、自定義@DataSource注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {

  String name() default "master";
}

7、Aop切面類配置

@Component
@Aspect
public class DataSourceAspect {

  @Pointcut("@annotation(com.zxgeo.sso.muiltDatasource.anons.DataSource)")
  public void dataSourcePointCut(){}

  @Around(value = "dataSourcePointCut()")
  public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();

    DataSource dataSource = method.getAnnotation(DataSource.class);
    if(dataSource == null){
      DynamicDataSource.setDataSource("master");
    }else {
      DynamicDataSource.setDataSource(dataSource.name());
    }
    try {
      return point.proceed();
    } finally {
      DynamicDataSource.clearDataSource();
    }
  }
}

8、啟動配置注解信息,重要(不然運行會報錯)

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})

9、測試

(1)、service層(此處沒有使用mybatis)

@Service
public class TestService {

  @Autowired
  private javax.sql.DataSource dataSource;

  @DataSource
  public Map<String,Object> getMasterDataSource() throws SQLException {
    Connection connection = dataSource.getConnection();
    Map<String,Object> map;
    try (PreparedStatement preparedStatement
           = connection.prepareStatement("SELECT * FROM AA WHERE A=10001")) {
      ResultSet resultSet = preparedStatement.executeQuery();
      map = new HashMap<>();
      while (resultSet.next()){
        map.put("A",resultSet.getString("A"));
        map.put("B",resultSet.getString("B"));
        map.put("C",resultSet.getString("C"));
      }
    }
    return map;
  }
  @DataSource(name = "slave")
  public Map<String,Object> getSlaveDataSource() throws SQLException {
    Connection connection = dataSource.getConnection();
    Map<String,Object> map;
    try (PreparedStatement preparedStatement
           = connection.prepareStatement("SELECT * FROM AA WHERE A=10002")) {
      ResultSet resultSet = preparedStatement.executeQuery();
      map = new HashMap<>();
      while (resultSet.next()){
        map.put("A",resultSet.getString("A"));
        map.put("B",resultSet.getString("B"));
        map.put("C",resultSet.getString("C"));
      }
    }
    return map;
  }
}

(2)、單元測試

@SpringBootTest
@RunWith(SpringRunner.class)
class SsoApplicationTests {

  @Autowired
  private TestService testService;

  @Test
  public void muliDatasorce() throws SQLException {
    Map<String, Object> masterDataSourceUrl = testService.getMasterDataSource();
    System.out.println(masterDataSourceUrl);
    Map<String, Object> slaveDataSourceUrl = testService.getSlaveDataSource();
    System.out.println(slaveDataSourceUrl);
  }
}

(3)、結果:

spring boot多數據源動態切換代碼實例

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

竹山县| 邛崃市| 巫山县| 琼中| 治县。| 修水县| 泊头市| 晋城| 新邵县| 莆田市| 锦屏县| 湖口县| 色达县| 嘉义市| 方山县| 沂水县| 邵东县| 无极县| 浑源县| 贺州市| 深圳市| 遂川县| 新干县| 铁岭市| 花莲县| 曲靖市| 辉县市| 交口县| 聂荣县| 孝义市| 威信县| 齐齐哈尔市| 通榆县| 桦南县| 武功县| 常山县| 阳春市| 苗栗县| 泗洪县| 婺源县| 龙陵县|