簡體   English   中英

多個servlet可以綁定到同一個數據源(JNDI)嗎?

[英]Can multiple servlets bind to the same datasource (JNDI)?

我在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)。

謝謝!

據我所知,您不必為每個servlet指定唯一的數據源。

我正在開發一個Java EE Web應用程序,其中包含多個servlet,它們都使用一個數據源連接到DB。 此Web應用程序使用Oracle作為后端,使用WebLogic Server作為應用程序服務器。

在此Web應用程序的體系結構中,有一個用於連接到DB的專用類。 所有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...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM