我在项目中使用Spring Restful Web服务,这里有两类用户

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

2)间(11至12日的学生学习班)。

在每个URI中,我们指定用户类型,例如,如下所示:
http://localhost:8080/TestProject/login/次要/身份验证)

对于上述请求,我需要从“辅助” d.b表中获取数据。

同样,对于其他用户类型请求,需要与其他d.b(Inter)进行通信。

在“ DAO”课程中:

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服务器中,我配置了连接池。

server.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" />


context.xml

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


每次都加载数据源对象是一种好习惯吗?

请提出是否有更好的方法。

最佳答案

每次都加载数据源对象是一种好习惯吗?


  
    不,IMV。
  


将两个datasources (secondaryDS, interDS)定义为spring bean,默认情况下为singleton,然后根据需要将相应的datasource注入JDBCTemplate class。

关于java - 如何根据Java Web应用程序中的用户请求在两个数据库之间切换?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33340697/

10-09 06:17
查看更多