【问题标题】:Can multiple servlets bind to the same datasource (JNDI)?多个 servlet 可以绑定到同一个数据源 (JNDI) 吗?
【发布时间】:2012-01-25 13:10:31
【问题描述】:

我的 Jetty.xml 文件中设置了一个数据源,如下所示:

<New id="MySQL_DS" class="org.eclipse.jetty.plus.jndi.Resource">
  <Arg></Arg>
  <Arg>jdbc/MySQL_DS</Arg>
  <Arg>
    <New class="com.mchange.v2.c3p0.ComboPooledDataSource">
      <Set name="driverClass">com.mysql.jdbc.Driver</Set>
      <Set name="jdbcUrl">jdbc:mysql:[IP]</Set>
      <Set name="user">[USER]</Set>
      <Set name="password">[PASSWORD]</Set>
      <Set name="checkoutTimeout">5000</Set>
      <Set name="initialPoolSize">3</Set>
      <Set name="maxIdleTime">3600</Set>
      <Set name="maxPoolSize">50</Set>
      <Set name="minPoolSize">1</Set>
      <Set name="maxStatements">200</Set>
      <Set name="maxConnectionAge">0</Set>
      <Set name="acquireIncrement">3</Set>
    </New>
  </Arg>
</New>

它在我的 web.xml 中定义如下:

<resource-ref>
  <description>DB Connection</description>
  <res-ref-name>jdbc/MySQL_DS</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

我在我的 servlet 代码中像这样绑定到我的数据源:

InitialContext ctx = new InitialContext();
_dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/MySQL_DS");

我的问题是:

我需要在同一个数据源上使用 4 个使用此上下文查找的 servlet。这样的事情有可能吗?

我的意思是,多个 servlet 可以绑定到同一个数据源,还是每个 servlet 必须有自己的?

我问这个是因为我有一个 servlet 工作正常,但另一个抛出 javax.naming.NameNotFoundException(剩余名称 jdbc/MySQL_DS)。

谢谢!

【问题讨论】:

    标签: java jetty jndi c3p0


    【解决方案1】:

    据我所知,您不必为每个 servlet 指定唯一的数据源。

    我正在开发一个 Java EE Web 应用程序,其中包含多个 servlet,它们都使用一个数据源连接到数据库。此 Web 应用程序使用 Oracle 作为后端,使用 WebLogic Server 作为应用程序服务器。

    在这个 Web 应用程序的架构中,有一个用于连接数据库的专用类。所有的 servlet 都会调用这个类来连接到 DB。

    这个连接类在构造函数中有以下几行(类似于你上面的)...

    InitialContext ic=new InitialContext();
    DataSource ds=(DataSource) ic.lookup("jdbc/OracleDS");
    con=ds.getConnection("user","pwd"); \\ ("con" is a private Connection instance var)

    然后,每个 servlet 只需使用连接类连接到 DB。

    比如……

    MyConnectionClass con = new MyConnectionClass(); // ("MyConnectionClass" is where the data source info is...)
    PreparedStatement ps=con.prepareStatement("SELECT * FROM SOME_TABLE");
    ResultSet rs=ps.executeQuery();
    more code below...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 2017-01-04
      相关资源
      最近更新 更多