我的猜測是,這可能被看作是一個多租戶方式,一個租戶將只讀,其他租戶將寫。
的步驟來配置持久層爲多租戶支持包括:
application.yml
...
multitenancy:
dvdrental:
dataSources:
-
tenantId: readonly
url: jdbc:postgresql://172.16.69.133:5432/db_dvdrental
username: user_dvdrental
password: changeit
driverClassName: org.postgresql.Driver
-
tenantId: write
url: jdbc:postgresql://172.16.69.133:5532/db_dvdrental
username: user_dvdrental
password: changeit
driverClassName: org.postgresql.Driver
...
MultiTenantJpaConfiguration.java
...
@Configuration
@EnableConfigurationProperties({ MultiTenantDvdRentalProperties.class, JpaProperties.class })
@ImportResource(locations = { "classpath:applicationContent.xml" })
@EnableTransactionManagement
public class MultiTenantJpaConfiguration {
@Autowired
private JpaProperties jpaProperties;
@Autowired
private MultiTenantDvdRentalProperties multiTenantDvdRentalProperties;
...
}
MultiTenantDvdRentalProperties.java
...
@Configuration
@ConfigurationProperties(prefix = "multitenancy.dvdrental")
public class MultiTenantDvdRentalProperties {
private List<DataSourceProperties> dataSourcesProps;
// Getters and Setters
public static class DataSourceProperties extends org.springframework.boot.autoconfigure.jdbc.DataSourceProperties {
private String tenantId;
// Getters and Setters
}
}
MultiTenantJpaConfiguration.java
...
public class MultiTenantJpaConfiguration {
...
@Bean(name = "dataSourcesDvdRental")
public Map<String, DataSource> dataSourcesDvdRental() {
...
}
...
}
MultiTenantJpaConfiguration.java
...
public class MultiTenantJpaConfiguration {
...
@Bean
public MultiTenantConnectionProvider multiTenantConnectionProvider() {
...
}
@Bean
public CurrentTenantIdentifierResolver currentTenantIdentifierResolver() {
...
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(MultiTenantConnectionProvider multiTenantConnectionProvider,
CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {
...
}
...
}
MultiTenantJpaConfiguration.java
...
public class MultiTenantJpaConfiguration {
...
@Bean
public EntityManagerFactory entityManagerFactory(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
...
}
@Bean
public PlatformTransactionManager txManager(EntityManagerFactory entityManagerFactory) {
...
}
...
}
applicationContent.xml
...
<jpa:repositories base-package="com.asimio.dvdrental.dao" transaction-manager-ref="txManager" />
<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />
...
ActorDao。java的
public interface ActorDao extends JpaRepository<Actor, Integer> {
}
根據您的需求這樣的事情可以做:
...
@Autowired
private ActorDao actorDao;
...
// Read feature
...
DvdRentalTenantContext.setTenantId("readonly");
this.actorDao.findOne(...);
...
// Or write
DvdRentalTenantContext.setTenantId("write");
this.actorDao.save(...);
...
設置tenantId可以在Servlet過濾器/ Spring MVC的攔截器/線程將要執行的JPA完成操作等
大約多租戶方式的更多細節可以在我的博客上找到在http://tech.asimio.net/2017/01/17/Multitenant-applications-using-Spring-Boot-JPA-Hibernate-and-Postgres.html
@Oliver基爾克你有什麼婆感謝! – Coder