dynamiczna zmiana źródła danych

Mam aplikację Spring, chcę dynamicznie zmieniać źródło danych, tj. po wprowadzeniu DS URL, Spring beans i wszystkie zależności zostaną zaktualizowane automatycznie.Wiem, że to trochę dziwne, ale w każdym razie chcę to osiągnąć. Moja konfiguracja sprężynowa w następujący sposób:

<bean id="majorDataSource" class="org.postgresql.ds.PGSimpleDataSource">
    <property name="serverName" value="${jdbc.serverName}" />
    <property name="portNumber" value="${jdbc.portNumber}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="databaseName" value="${jdbc.databaseName}" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="majorDataSource"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="majorDataSource"/>
    <property name="configLocation" value="classpath:sqlmap-config.xml"/>
</bean>

Pytania są następujące:

  1. Adres URL JDBC jest przechowywany we właściwościach, które można zmienić w trybie runtime.

  2. Po zmianie adresu URL muszę ponownie utworzyć źródło danych i może obiekty zależne. Nie mogłam wymyślić, jak zrobić to elegancko wiosną?

Wiedziałem, że Spring może dynamicznie trasować źródło danych na podstawie jednego klucza, ale adres URL źródła danych jest predefiniowany w Spring i nie zmieni trybu runtime. To nie moja sprawa.

Author: Simon Wang, 2012-11-22

2 answers

Możesz użyć Springa AbstractRoutingDataSource rozszerzając go i nadpisując metodę determineCurrentLookupKey(), która powinna zwrócić klucz odwołujący się do spring bean datasource.

Spójrz na ten artykuł na blogu spring source , który pokaże ci przykład, jak korzystać z tej funkcji.

Zasadniczo aby odpowiedzieć na twoje pytania, musisz zdefiniować dwa źródła danych jako różne spring bean w konfiguracji XML. Nie ma potrzeby Utwórz jedną dynamicznie, spring załaduje obie i użyje jednej lub drugiej dynamicznie w zależności od Twoich kryteriów w metodzie determineCurrentLookupKey().

To prowadziłoby do czegoś takiego:

XML config

<!-- first data source -->
<bean id="majorDataSource" class="org.postgresql.ds.PGSimpleDataSource">
    <property name="serverName" value="${jdbc.major.serverName}" />
    <property name="portNumber" value="${jdbc.major.portNumber}" />
    <property name="user" value="${jdbc.major.username}" />
    <property name="password" value="${jdbc.major.password}" />
    <property name="databaseName" value="${jdbc.major.databaseName}" />
</bean>
<!-- second data source -->
<bean id="minorDataSource" class="org.postgresql.ds.PGSimpleDataSource">
    <property name="serverName" value="${jdbc.minor.serverName}" />
    <property name="portNumber" value="${jdbc.minor.portNumber}" />
    <property name="user" value="${jdbc.minor.username}" />
    <property name="password" value="${jdbc.minor.password}" />
    <property name="databaseName" value="${jdbc.minor.databaseName}" />
</bean>
<!-- facade data source -->
<bean id="dataSource" class="blog.datasource.CustomerRoutingDataSource">
   <property name="targetDataSources">
      <map>
         <entry key="MINOR" value-ref="minorDataSource"/>
         <entry key="MAJOR" value-ref="majorDataSource"/>
      </map>
   </property>
   <property name="defaultTargetDataSource" ref="majorDataSource"/>
</bean>
<!-- wiring up -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:sqlmap-config.xml"/>
</bean>

Java

public class MyRoutingDataSource extends AbstractRoutingDataSource {
   @Override
   protected Object determineCurrentLookupKey() {
      // get the current url
      HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
      if (request.getRequestURL().toString().endsWith("/minor"))
          return "MINOR";
      else
          return "MAJOR";
   }
}
 26
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-22 08:20:20

Nie jestem pewien, czy to jest właściwy sposób, ale to, co możesz zrobić, to coś takiego.

<bean id="majorDataSource" class="org.postgresql.ds.PGSimpleDataSource">
    <property name="serverName" value="dummydata" />
    <property name="portNumber" value="dummydata" />
    <property name="user" value="dummydata" />
    <property name="password" value="dummydata" />
    <property name="databaseName" value="dummydata" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="majorDataSource"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

Oraz w klasie Java

public class TestTransaction {

   @Autowired
   private DataSourceTransactionManager manager;

   private PlatformTransactionManager transactionManager;

   public testExecution(DataSource ds) {
       manager.setDataSource(ds);
       transactionManager = manager;
       TransactionDefinition def = new DefaultTransactionDefinition();
       TransactionStatus status = transactionManager.getTransaction(def);
       try {
           jdbcTemplate.update();
           transactionManager.commit(status);
       } catch (Exception ex) {
           transactionManager.rollback(status);
       }
   }
}

Proszę zasugerować, czy to podejście może działać, ponieważ jestem jeszcze Nowy na wiosnę

 0
Author: Jashan Preet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-30 13:20:25