如何为mybatis实现quarkus-dynamic-multi-tenant?

问题描述 投票:0回答:1

如何为mybatis实现quarkus-dynamic-multi-tenant?

quarkus mybatis 是否可以实现动态切换数据源目前没有找到好的办法 quarkus mybatis可以实现数据源的动态切换吗?目前还没有找到好的解决方案

mybatis 扩展 https://github.com/quarkiverse/quarkus-mybatis

类似:这是hibernate:https://github.com/MossabTN/quarkus-dynamic-multi-tenant

quarkus mybatis multi-tenant
1个回答
0
投票

这是

javax.sql.DataSource
界面的力量。如果您提供自己的数据源实现,可以动态查找租户的实际底层数据源,您就可以使任何内容与多个数据源通信。其实没那么难。

import javax.sql.*;

public class MultiTenentDataSource implements DataSource {
    private ThreadLocal<String> tenant = new ThreadLocal<>();
    private Map<String,DataSource> tenantSources = new ConcurrentHashMap<>();

    public <R> R bindTenant(String tenant, Callable<R> context) throws Exception {
        try {
           tenant.set( tenant );
           context.call();
        } finally {
           tenant.remove();
        }
    }

    Connection getConnection() {
        String current = tenant.get();
        if( current == null ) throw new IllegalArgumentException("Unassigned tenant to thread: " + Thread.currentThread().getName() );
        DataSource currentDataSource = tenantSources.get( tenant );
        if( currentDataSource != null ) {
            return currentDataSource.getConnection();
        } else {
            DataSource tenantDs = new MysqlDataSource();
            tenantDs.setDatabaseName( tenant + "Db" );
            ...
            tenants.put( tenant, tenantDs );
            return tenantDs.getConnection();
        }
    }

    Connection getConnection(String username, String password) {
       // implement something similar for username / password
    }

    ....
}

然后只需将其设置为 Quarkus 中的数据源并用它初始化 My-Batis。在请求处理期间,在 Web 容器的过滤器中添加对 bindTenant() 的调用,以及 viola 多租户魔法。

© www.soinside.com 2019 - 2024. All rights reserved.