【发布时间】:2021-04-19 16:03:04
【问题描述】:
我正在努力寻找一种方法来为每个请求在 DSLContext 中定义一些设置。
我想要达到的目标如下:
我有一个 springboot API 和一个具有多个共享相同结构的模式的数据库。 根据每个请求的某些参数,我想连接到一个特定的架构,如果没有设置参数,我想连接到任何架构并失败。
为了不连接到任何架构,我写了以下内容:
@Autowired
public DefaultConfiguration defaultConfiguration;
@PostConstruct
public void init() {
Settings currentSettings = defaultConfiguration.settings();
Settings newSettings = currentSettings.withRenderSchema(false);
defaultConfiguration.setSettings(newSettings);
}
我认为效果很好。
现在我需要一种方法来为每个请求在 DSLContext 中设置模式,因此每次在请求期间使用 DSLContext 时,我都会自动获得与该模式的连接,而不会影响其他请求。 我的想法是拦截请求,获取参数并执行“DSLContext.setSchema()”之类的操作,但以适用于当前请求期间所有 DSLContext 使用的方式。
我尝试定义一个自定义ConnectionProvider的请求scopeBean如下:
@Component
@RequestScope
public class ScopeConnectionProvider implements ConnectionProvider {
@Override
public Connection acquire() throws DataAccessException {
try {
Connection connection = dataSource.getConnection();
String schemaName = getSchemaFromRequestContext();
connection.setSchema(schemaName);
return connection;
} catch (SQLException e) {
throw new DataAccessException("Error getting connection from data source " + dataSource, e);
}
}
@Override
public void release(Connection connection) throws DataAccessException {
try {
connection.setSchema(null);
connection.close();
} catch (SQLException e) {
throw new DataAccessException("Error closing connection " + connection, e);
}
}
}
但此代码仅在第一个请求时执行。以下请求不执行此代码,因此它使用第一个请求的架构。
关于如何做到这一点的任何提示?
谢谢
【问题讨论】:
标签: spring-boot jooq