有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring如何根据Java web应用程序中的用户请求在两个数据库之间切换?

我在我的项目中使用SpringRESTfulWeb服务,这里我有两类用户

1)中学(6至10年级的学生)

2)校际(11至12年级之间的学生学习班)

在每个URI中,我们指定用户类型,例如,请参见下文: (http://localhost:8080/TestProject/login/次要/authenticate)

对于上述请求,我需要从'secondary'd.b表中获取数据

类似地,对于其他用户类型的请求,需要与其他d.b(Inter)通信

在“道”类中:

NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(
            getDataSource());
    jdbcTemplate.getJdbcOperations().execute(
                "SET SCHEMA " + **UriUtils.getSchema()**);

在上面的UriUtils中。getSchema(),方法返回“数据库”名称

private DataSource getDataSource() {
    String db = UriUtils.getDataBaseName();
    DataSource dataSource = null;
    try {
        InitialContext initialContext = new InitialContext();
        Context environmentContext = (Context) initialContext
                .lookup("java:comp/env");
        dataSource = (DataSource) environmentContext.lookup(db);
    } catch (NamingException e) {
        logger.error(e.getMessage());
        logger.info(db + " resource is not available in server.xml file");
        e.printStackTrace();
    }
    return dataSource;
}

在Tomcat服务器中,我配置了连接池

服务器。xml

<Resource auth="Container" driverClassName="org.postgresql.Driver"
        logAbandoned="true" maxActive="20" maxIdle="10" maxWait="-1"
        name="secondary" password="admin" removeAbandoned="true"
        removeAbandonedTimeout="90" type="javax.sql.DataSource"
        url="jdbc:postgresql://localhost:5432/postgres?currentSchema=secondary"
        username="postgres" />
    <Resource auth="Container" driverClassName="org.postgresql.Driver"
        logAbandoned="true" maxActive="20" maxIdle="10" maxWait="-1"
        name="inter" password="admin" removeAbandoned="true"
        removeAbandonedTimeout="90" type="javax.sql.DataSource"
        url="jdbc:postgresql://localhost:5432/postgres?currentSchema=inter"
        username="postgres" />

上下文。xml

<ResourceLink name="secondary" global="secondary"
    type="org.postgresql.Driver" />
<ResourceLink name="inter" global="inter"
    type="org.postgresql.Driver" />

每次加载数据源对象是否是一种好的做法

请建议是否有更好的方法可用


共 (2) 个答案

  1. # 1 楼答案

    您不会每次都加载数据库。查找操作未加载数据库。可以对每个请求执行查找。另外,我在您的示例中没有看到两个数据库。在一个postgresql数据库上有两个数据源。您可以使用一个数据源,并对模式切换的每个客户端请求执行SET SCHEMA

  2. # 2 楼答案

    每次加载数据源对象是一种好的做法吗

    NO, IMV.

    将两个datasources (secondaryDS, interDS)定义为SpringBeans默认为singleton,并根据需要将相应的datasource注入JDBCTemplate