欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot添加多數據源的方法實例教程

 更新時間:2023年09月12日 10:51:51   作者:清風怎不知意  
這篇文章主要給大家介紹了關于springboot添加多數據源方法的相關資料,在實際開發(fā)中經??赡苡龅皆谝粋€應用中可能要訪問多個數據庫多的情況,需要的朋友可以參考下

前言

Spring Boot可以通過配置多個數據源來支持多數據源訪問,以下是一個基本的多數據源配置實例:

添加多數據源的配置類

創(chuàng)建一個配置類來配置多個數據源,可以使用@Configuration和@Primary注解來標識主數據源,示例代碼如下:

@Configuration
public class DataSourceConfig {
    @Bean(name = "primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

在這個配置類中,我們定義了兩個數據源,一個是主數據源,一個是次要數據源。我們使用@ConfigurationProperties注解來設置每個數據源的配置參數。

在application.yml中添加數據源配置

添加application.yml配置文件,并在文件中添加多個數據源的配置信息,例如:

spring:
  datasource:
    primary:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test1
      username: root
      password: root
    secondary:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/test2
      username: root
      password: root

我們使用了Spring Boot的默認配置規(guī)則,通過指定數據源的名稱和屬性前綴來配置每個數據源。

配置JdbcTemplate來訪問多個數據源

現在我們已經定義了兩個數據源,我們需要配置JdbcTemplate來訪問它們。我們可以在使用JdbcTemplate的每個方法中指定要使用的數據源,示例代碼如下:

@Repository
public class UserRepository {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;
    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;
    public List<User> getUsersFromPrimary() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(primaryDataSource);
        List<User> users = jdbcTemplate.query("SELECT * FROM users", new BeanPropertyRowMapper(User.class));
        return users;
    }
    public List<User> getUsersFromSecondary() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(secondaryDataSource);
        List<User> users = jdbcTemplate.query("SELECT * FROM users", new BeanPropertyRowMapper(User.class));
        return users;
    }
}

我們在注入JdbcTemplate之前使用@Autowired注解將每個數據源注入到存儲庫類中。然后,我們可以在每個方法中使用JdbcTemplate來訪問不同的數據源。

這是一個基本的多數據源配置實例,你可以在此基礎上進一步調整以滿足你的具體需求。

如果你使用的是MyBatis框架,你可以使用MyBatis的動態(tài)數據源來實現多數據源配置,具體步驟如下

定義數據源配置類

首先,你需要定義一個數據源配置類來讀取和解析配置文件,然后根據配置創(chuàng)建數據源并將其添加到數據源列表中,示例代碼如下:

@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource());
        targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
        return dynamicDataSource;
    }
}

在這個配置類中,我們使用@ConfigurationProperties注解來讀取每個數據源的配置信息,然后使用DataSourceBuilder創(chuàng)建數據源對象。接著,我們使用DynamicDataSource類來管理多個數據源,將所有數據源添加到targetDataSources中并設置默認數據源為masterDataSource。

實現動態(tài)數據源

接下來,你需要實現一個動態(tài)數據源,它可以根據需要選擇不同的數據源,示例代碼如下:

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}

我們繼承了AbstractRoutingDataSource類,覆蓋了它的determineCurrentLookupKey()方法來獲取當前線程所需的數據源類型,并返回數據源名稱。

實現數據源上下文

最后,你需要創(chuàng)建一個數據源上下文來保存當前線程所需的數據源類型,示例代碼如下:

public class DynamicDataSourceContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }
    public static String getDataSourceType() {
        return contextHolder.get();
    }
    public static void clearDataSourceType() {
        contextHolder.remove();
    }
}

我們使用了ThreadLocal來保存當前線程所需的數據源類型。你可以在需要訪問不同數據源的方法中調用setDataSourceType()方法來設置當前線程所需的數據源類型,調用clearDataSourceType()方法來清除上下文。

最后,在你的MyBatis配置文件中,你可以使用${}占位符引用定義的動態(tài)數據源,示例代碼如下:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dynamicDataSource"/>
    <property name="typeAliasesPackage" value="com.example.model"/>
</bean>

我們將MyBatis的SqlSessionFactoryBean中的dataSource屬性設置為定義的動態(tài)數據源dynamicDataSource即可。

切換數據源

最后,你可以在需要訪問不同數據源的方法中調用DynamicDataSourceContextHolder.setDataSourceType()方法來設置當前線程所需的數據源類型。例如,你可以定義一個注解來標識使用哪個數據源,然后在方法上加上這個注解即可自動切換數據源。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    DataSourceType value() default DataSourceType.MASTER;
}
@Aspect
@Component
public class DynamicDataSourceAspect {
    @Pointcut("@annotation(com.example.annotation.DataSource)")
    public void dataSourcePointcut() {
    }
    @Before("dataSourcePointcut()")
    public void before(JoinPoint joinPoint) {
        DataSource dataSource = getDataSource(joinPoint);
        if (dataSource != null) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
    }
    @After("dataSourcePointcut()")
    public void after(JoinPoint joinPoint) {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
    private DataSource getDataSource(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        if (method.isAnnotationPresent(DataSource.class)) {
            return method.getAnnotation(DataSource.class);
        }
        return null;
    }
}

在這個例子中,我們定義了一個@DataSource注解來標識使用哪個數據源,然后使用AOP來自動切換數據源。在DynamicDataSourceAspect類中,我們使用@Pointcut注解來定義切點,然后使用@Before和@After注解來分別在方法調用前和方法調用后切換數據源。在切換數據源時,我們可以通過getDataSource()方法獲取方法上的@DataSource注解,并使用注解中定義的數據源類型來設置當前線程所需的數據源類型。

總結

到此這篇關于springboot添加多數據源方法的文章就介紹到這了,更多相關springboot添加多數據源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Spring依賴注入中的@Resource與@Autowired詳解

    Spring依賴注入中的@Resource與@Autowired詳解

    這篇文章主要介紹了Spring依賴注入中的@Resource與@Autowired詳解,提到Spring依賴注入,大家最先想到應該是@Resource和@Autowired,對于Spring為什么要支持兩個這么類似的注解卻未提到,屬于知其然而不知其所以然,本文就來做詳細講解,需要的朋友可以參考下
    2023-09-09
  • 基于JAVA每月運勢api調用代碼實例

    基于JAVA每月運勢api調用代碼實例

    這篇文章主要為大家詳細介紹了JAVA每月運勢api調用代碼實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • MyBatis中多對多關系的映射和查詢

    MyBatis中多對多關系的映射和查詢

    本文主要介紹了MyBatis中多對多關系的映射和查詢的相關知識。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02
  • 如何在logback日志配置里獲取服務器ip和端口

    如何在logback日志配置里獲取服務器ip和端口

    這篇文章主要介紹了如何在logback日志配置里獲取服務器ip和端口的方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Spring中的事件監(jiān)聽器使用學習記錄

    Spring中的事件監(jiān)聽器使用學習記錄

    Spring框架中的事件監(jiān)聽機制是一種設計模式,它允許你定義和觸發(fā)事件,同時允許其他組件監(jiān)聽這些事件并在事件發(fā)生時作出響應,這篇文章主要介紹了Spring中的事件監(jiān)聽器使用學習,需要的朋友可以參考下
    2024-07-07
  • java實現俄羅斯方塊

    java實現俄羅斯方塊

    這篇文章主要為大家詳細介紹了java實現俄羅斯方塊,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Javaweb項目session超時解決方案

    Javaweb項目session超時解決方案

    這篇文章主要介紹了Javaweb項目session超時解決方案,關于解決方案分類比較明確,內容詳細,需要的朋友可以參考下。
    2017-09-09
  • SpringBoot項目中Druid自動登錄功能實現

    SpringBoot項目中Druid自動登錄功能實現

    Druid是Java語言中最好的數據庫連接池,Druid能夠提供強大的監(jiān)控和擴展功能,這篇文章主要介紹了SpringBoot項目中Druid自動登錄功能實現,需要的朋友可以參考下
    2024-08-08
  • Spring AOP實現Redis緩存數據庫查詢源碼

    Spring AOP實現Redis緩存數據庫查詢源碼

    這篇文章主要介紹了Spring AOP實現Redis緩存數據庫查詢的相關內容,源碼部分還是不錯的,需要的朋友可以參考下。
    2017-09-09
  • Eclipse添加xml文件提示及Hibernate配置學習

    Eclipse添加xml文件提示及Hibernate配置學習

    文件提示功能在開發(fā)過程中很實用的,本文實現了一個Eclipse添加xml文件提示,感興趣的朋友可以了解下啊,希望本文對你有所幫助
    2013-01-01

最新評論