每个请求的 Jooq 配置

Jooq configuration per request

我正在努力寻找一种方法来根据请求在 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);
        }
    }
}

但是这段代码只在第一次请求时执行。以下请求不执行此代码,因此它使用第一个请求的模式。

关于如何做到这一点的任何提示?

谢谢

您的请求范围 bean 似乎被注入到单例中。
您已经在使用 @RequestScope 这很好,但是您可能忘记在 Spring 配置 class.

上添加 @EnableAspectJAutoProxy
@Configuration
@EnableAspectJAutoProxy
class Config {

}

这将使您的 bean 运行 在单例内部的代理中,因此会根据请求进行更改。

没关系,看来我遇到的问题是由我定义的某些可缓存函数的意外行为引起的。尽管输入不同,但该函数正在从缓存中返回一个值,这就是没有获取新连接的原因。我仍然需要弄清楚是什么原因导致了这种意想不到的行为。

目前,我会坚持使用这种方法,因为它在概念层面上看起来不错,尽管我希望有更好的方法来做到这一点。

*** 更新 *** 我发现这是缓存的问题

*** 更新 2 *** 似乎忽略了底层数据源中的设置模式。我目前正在尝试我刚刚发现的另一种方法 (https://github.com/LinkedList/spring-jooq-multitenancy)