Spring Boot + JPA动态数据源

时间:2019-03-18 15:32:38

标签: spring spring-boot jpa

我遇到一种情况,我需要根据用户输入创建一个数据库连接,并且该创建的连接应用于所有事务,直到该特定用户注销为止。我需要在Spring Boot + JPA中执行此操作。默认情况下,我在服务器启动时从yaml文件中获取连接详细信息。

我很困惑如何创建新数据源并将其用于整个会话。

我是Spring Boot和JPA的新手。有人可以帮我举个例子吗。

1 个答案:

答案 0 :(得分:0)

这不是快速解决方案,可能需要一天左右的时间才能正确实现 ,但是使用Oracle proxy connection可以使您获得普通JDBC的速度池,但每个用户将对数据库具有其特定权限。审计跟踪还将获取代理的用户。

使用Spring登录用户来确定要代理的用户。

您将需要从Oracle JDBC page下载两个依赖项。 确保版本相同。将它们安装在您的Maven仓库中。

<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ucp</artifactId>
    <version>12.2.0.1.0</version>
</dependency>
<dependency>
    <groupId>com.oracle.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>12.2.0.1.0</version>
    <scope>provided</scope>
</dependency>

为Spring提供数据源。

import oracle.ucp.UniversalConnectionPool;
import oracle.ucp.UniversalConnectionPoolAdapter;
import oracle.ucp.admin.UniversalConnectionPoolManager;
import oracle.ucp.admin.UniversalConnectionPoolManagerImpl;
import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;

@Bean
@SneakyThrows
public DataSource dataSource() throws SQLException {
    final PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();
    UniversalConnectionPoolManager mgr = UniversalConnectionPoolManagerImpl.getUniversalConnectionPoolManager();

    pds.registerConnectionLabelingCallback(new MyProxyConnectionLabelingCallback("MY_NOPRIV"));//you can make this any name you want
    DataSource result = new ProxyDelegatingDataSource(pds, getNoPrivilegesUser());

    mgr.createConnectionPool((UniversalConnectionPoolAdapter) pds);
    mgr.startConnectionPool(PROXY_UCP_NAME);
    return result;
}

实施ConnectionLabelingCallback并了解费用是什么。

import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import oracle.jdbc.OracleConnection;
import oracle.ucp.ConnectionLabelingCallback;
import oracle.ucp.jdbc.LabelableConnection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class MyProxyConnectionLabelingCallback implements ConnectionLabelingCallback {

    public static final String USER_PROXY = "USER_PROXY";

    private final String noPrivilegesUser;

    public ProxyConnectionLabelingCallback(String noPrivilegesUser) {
        this.noPrivilegesUser = noPrivilegesUser;
    }

    @Override
    public int cost(Properties reqLabels, Properties currentLabels) {
        final Object request = reqLabels.get(USER_PROXY);
        final Object current = currentLabels.get(USER_PROXY);
        if (request.equals(current)) {
            //Same user
            return 0;
        }
        if (noPrivilegesUser.equals(current)) {
            //No Priv User. No Little Cost
            return 1;
        }
        //Different user request

        return 1000;
    }

    @Override
    public boolean configure(Properties reqLabels, Object conn) {
        try {
            LabelableConnection lConn = (LabelableConnection) conn;
            String userName = getUserName(noPrivilegesUser);
            final Properties connectionLabels = lConn.getConnectionLabels();
            if (connectionLabels == null) {
                setProxy((OracleConnection) conn, noPrivilegesUser, userName, null);
                lConn.applyConnectionLabel(USER_PROXY, userName);
                return true;
            }
            Object currentLabel = connectionLabels.get(USER_PROXY);
            if (!userName.equals(currentLabel)) {
                setProxy((OracleConnection) conn, currentLabel, userName, null);
                lConn.applyConnectionLabel(USER_PROXY, userName);
            } else {
                //Label match, good
            }
            return true;
        } catch (SQLException| RuntimeException sExp) {
            return false;
        }
    }

    public static String getUserName(String noPrivilegesUser) {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();// you are logged with this user using Spring Security
        if ((authentication == null)) {
            //Not logged in returning non privileged user
            return noPrivilegesUser;
        }
        Object principal = authentication.getPrincipal();
        if (principal.equals("anonymousUser")) {
            //Not logged in returning non privileged user
            return noPrivilegesUser;
        }
        if (principal instanceof UserDetails) {
            final String username = ((UserDetails) (principal)).getUsername();
            //proxy connection to user  username
            return username;
        } else {
            return principal.toString();
        }
    }

    public void setProxy(OracleConnection oraCon, Object currentLabel, String proxyUserName, String proxyPassword) throws SQLException {
        if (oraCon.isProxySession()) {
            oraCon.close(OracleConnection.PROXY_SESSION);
        }

        Properties proxyProperties = new Properties();
        proxyProperties.setProperty(OracleConnection.PROXY_USER_NAME, proxyUserName);
        if (proxyPassword != null) {
            proxyProperties.setProperty(OracleConnection.PROXY_USER_PASSWORD, proxyPassword);
        }
        //below is what can take a few ms
        oraCon.openProxySession(OracleConnection.PROXYTYPE_USER_NAME, proxyProperties);
    }
}


import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.ucp.jdbc.PoolDataSource;
import org.springframework.jdbc.datasource.DelegatingDataSource;

class ProxyDelegatingDataSource extends DelegatingDataSource {

    private final PoolDataSource pds;
    private final String noPrivilegesUser;

    public ProxyDelegatingDataSource(PoolDataSource pds, String noPrivilegesUser) {
        super(pds);
        this.pds = pds;
        this.noPrivilegesUser = noPrivilegesUser;
    }

    @Override
    public Connection getConnection() throws SQLException {
        Properties prprts = new Properties();
        prprts.put(ProxyConnectionLabelingCallback.USER_PROXY, getUserName());
        return getConnection(prprts);
    }

    public Connection getConnection(Properties prprts) throws SQLException {
        return pds.getConnection(prprts);
    }

    public Connection getConnection(String username, String password, Properties prprts) throws SQLException {
        return pds.getConnection(username, password, prprts);
    }

    private String getUserName() {
        return ProxyConnectionLabelingCallback.getUserName(noPrivilegesUser);
    }

}

设置Oracle特权:

create user JDBCPROXY identified by pass123;
create user MY_NOPRIV identified by pass123;
GRANT CONNECT TO JDBCPROXY;
GRANT CONNECT TO MY_NOPRIV;

alter user MY_NOPRIV grant connect through JDBCPROXY;
alter user USER1 grant connect through JDBCPROXY;

创建池时,所有用户将以JDBCPROXY代理,代理为MY_NOPRIV。 当“ USER1”登录时,它将切换到以USER1代理的JDBCPROXY。

设置Spring安全性并以“ USER1”身份登录。我不会说的。