我正在使用具有多个模式的单个数据库构建一个Multitenant saas应用程序;每个客户端一个模式。我使用Spring Boot 2.1.5、HiberNate 5.3.10以及兼容的Spring data jpa和postgres 11.2。
我关注了这篇博文https://dzone.com/articles/spring-boot-hibernate-multitenancy-implementation.
尝试调试代码,以下是我的发现:
* 对于数据源配置中提供的默认架构,Hibernate会正确验证架构。它在默认架构中创建缺少或新的表/实体。
* 租户标识符已正确解析,Hibernate使用此租户构建会话。
我已经在下面的存储库中上传了代码:
https://github.com/naveentulsi/multitenant-lithium
我在这里添加了一些重要的类。
@Component
@Log4j2
public class MultiTenantConnectionProviderImpl implements
MultiTenantConnectionProvider {
@Autowired
DataSource dataSource;
@Override
public Connection getAnyConnection() throws SQLException {
return dataSource.getConnection();
}
@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
connection.close();
}
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
final Connection connection = getAnyConnection();
try {
if (!StringUtils.isEmpty(tenantIdentifier)) {
String setTenantQuery = String.format(AppConstants.SCHEMA_CHANGE_QUERY, tenantIdentifier);
connection.createStatement().execute(setTenantQuery);
final ResultSet resultSet = connection.createStatement().executeQuery("select current_schema()");
if(resultSet != null){
final String string = resultSet.getString(1);
log.info("Current Schema" + string);
}
System.out.println("Statement execution");
} else {
connection.createStatement().execute(String.format(AppConstants.SCHEMA_CHANGE_QUERY, AppConstants.DEFAULT_SCHEMA));
}
} catch (SQLException se) {
throw new HibernateException(
"Could not change schema for connection [" + tenantIdentifier + "]",
se
);
}
return connection;
}
@Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
try {
String Query = String.format(AppConstants.DEFAULT_SCHEMA, tenantIdentifier);
connection.createStatement().executeQuery(Query);
} catch (SQLException se) {
throw new HibernateException(
"Could not change schema for connection [" + tenantIdentifier + "]",
se
);
}
connection.close();
}
@Override
public boolean supportsAggressiveRelease() {
return true;
}
@Override
public boolean isUnwrappableAs(Class unwrapType) {
return false;
}
@Override
public <T> T unwrap(Class<T> unwrapType) {
return null;
}
}
@Configuration
@EnableJpaRepositories
public class ApplicationConfiguration implements WebMvcConfigurer {
@Autowired
JpaProperties jpaProperties;
@Autowired
TenantInterceptor tenantInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tenantInterceptor);
}
@Bean
public DataSource dataSource() {
return DataSourceBuilder.create().username(AppConstants.USERNAME).password(AppConstants.PASS)
.url(AppConstants.URL)
.driverClassName("org.postgresql.Driver").build();
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, MultiTenantConnectionProviderImpl multiTenantConnectionProviderImpl, CurrentTenantIdentifierResolver currentTenantIdentifierResolver) {
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.ddl-auto", "update");
properties.put("hibernate.jdbc.lob.non_contextual_creation", "true");
properties.put("show-sql", "true");
properties.put("hikari.maximum-pool-size", "3");
properties.put("hibernate.default_schema", "master");
properties.put("maximum-pool-size", "2");
if (dataSource instanceof HikariDataSource) {
((HikariDataSource) dataSource).setMaximumPoolSize(3);
}
properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl);
properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
properties.put(Environment.FORMAT_SQL, true);
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.saas");
em.setJpaVendorAdapter(jpaVendorAdapter());
em.setJpaPropertyMap(properties);
return em;
}
}
@Component
public class TenantResolver implements CurrentTenantIdentifierResolver {
private static final ThreadLocal<String> TENANT_IDENTIFIER = new ThreadLocal<>();
public static void setTenantIdentifier(String tenantIdentifier) {
TENANT_IDENTIFIER.set(tenantIdentifier);
}
public static void reset() {
TENANT_IDENTIFIER.remove();
}
@Override
public String resolveCurrentTenantIdentifier() {
String currentTenant = TENANT_IDENTIFIER.get() != null ? TENANT_IDENTIFIER.get() : AppConstants.DEFAULT_SCHEMA;
return currentTenant;
}
@Override
public boolean validateExistingCurrentSessions() {
return true;
}
}
在租户解析程序成功注入 TenantId 后,实体管理器应该能够将实体存储到数据库中的相应租户架构中。也就是说,如果我们创建一个实体的对象并在 db 中保持不变,它应该成功保存在 db 中。但就我而言,实体不会保存到默认架构以外的任何架构中。
更新1:我能够使用mysql8.0.12进行多租户模式切换。但仍然无法使用postgres进行切换。
您应该使用AbstractRoutingDataSource来实现这一点,它在幕后执行所有的魔法,网上有许多示例,您可以在https://www . bael dung . com/spring-abstract-routing-data-source找到一个
在类“ApplicationConfiguration.java”中;
您必须删除此" properties . put(" hibernate . default _ schema "," master ");"为什么当你改变模式的时候,它会改变,但是当它一次又一次的到达这条线的时候,它会设置默认模式
我希望你得到了答案
谢谢你们所有人
保重!