Spring boot 每个请求的Jooq配置

Spring boot 每个请求的Jooq配置,spring-boot,jooq,Spring Boot,Jooq,我正在努力找到一种方法,在每个请求的DSLContext中定义一些设置 我希望实现以下目标: @Autowired public DefaultConfiguration defaultConfiguration; @PostConstruct public void init() { Settings currentSettings = defaultConfiguration.settings(); Settings newSettings = currentSetting

我正在努力找到一种方法,在每个请求的DSLContext中定义一些设置

我希望实现以下目标:

@Autowired
public DefaultConfiguration defaultConfiguration;

@PostConstruct
public void init() {
    Settings currentSettings = defaultConfiguration.settings();
    Settings newSettings = currentSettings.withRenderSchema(false);
    defaultConfiguration.setSettings(newSettings);
}
我有一个springbootapi和一个数据库,其中包含多个共享同一结构的模式。 根据每个请求的一些参数,我希望连接到一个特定的模式,如果没有设置任何参数,我希望连接到任何模式并失败

为了不连接到任何模式,我编写了以下代码:

@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配置类中添加
@enableSpectJautoproxy

@Configuration
@EnableAspectJAutoProxy
class Config {

}

这将使您的bean在singleton内部的代理中运行,因此每个请求都会更改。

不过,我遇到的问题似乎是由我定义的某个可缓存函数的意外行为引起的。函数从缓存返回一个值,尽管输入不同,这就是为什么不获取新连接的原因。我仍然需要弄清楚是什么导致了这种意想不到的行为

现在,我将坚持使用这种方法,因为它在概念层面上似乎很好,尽管我希望有更好的方法来做到这一点

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

***更新2*** 似乎忽略了在基础数据源中设置架构。我目前正在尝试我刚刚发现的另一种方法()