使用 Tomcat 7 (MySQL) 设置连接池

Setting up connection pool with Tomcat 7 (MySQL)

我正在使用 Tomcat 7.0.52 和 mysql-connector-java-5.1.36.jar。 我将 mysql jar 复制到 tomcat/lib 文件夹中。

DriverManager 工作,我可以获得连接并执行查询:

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, usr, pw);
Statement stmnt = con.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * FROM county");

但是我无法让它与连接池一起工作。

MyWebApp.war/WEB-INF/classes/Servu.class(此应用中只有 class,一个 servlet):

public class Servu extends HttpServlet {

    private static DataSource ds;

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("jdbc/maakler_new");
        } catch (ClassNotFoundException | NamingException ex) {
            Logger.getLogger(Servu.class.getName()).log(Level.SEVERE, "thrown from init()", ex);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Table:\n");
        try (PrintWriter out = resp.getWriter();
             Connection c = ds.getConnection();
             Statement stmnt = c.createStatement();
             ResultSet rs = stmnt.executeQuery("SELECT * FROM county");
        ) {
            while (rs.next()) {
                out.print(rs.getString(2) + "\n");
            }
            out.flush();
        } catch (SQLException ex) {
            Logger.getLogger(Servu.class.getName()).log(Level.SEVERE, "thrown from doGet()", ex);
        }
    }
}

MyWebApp.war\META-INF\context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Context>

      <Resource name="jdbc/maakler_new" auth="Container" type="javax.sql.DataSource"
               maxActive="40" maxIdle="30" maxWait="15000"
               username="user" password="pw" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://mydblocation.ee:3306/maakler_new"/>

</Context>

MyWebApp.war\WEB-INF\web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <servlet>
            <servlet-name>Servu</servlet-name>
            <servlet-class>Servu</servlet-class>
    </servlet>
    <servlet-mapping>
            <servlet-name>Servu</servlet-name>
            <url-pattern>/Servu</url-pattern>
    </servlet-mapping> 

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

</web-app>

如果我部署应用程序,我会收到此错误(来自 tomcat/logs/tomcat7-stderr.2015-10-31.log):

SEVERE: thrown from init()
javax.naming.NameNotFoundException: Name [jdbc/maakler_new] is not bound in this Context. Unable to find [jdbc].

为什么会出现此异常以及如何解决?

编辑1: 将 ResourceLink 添加到上下文,但仍然没有:

<Context>
            ...

       <ResourceLink global="jdbc/maakler_new" name="jdbc/maakler_new" type="javax.sql.DataSource" />

</Context>

编辑2: 这是我的 tomcat/conf/server.xml 文件:

<?xml version='1.0' encoding='utf-8'?>

  <GlobalNamingResources>

    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />

    <Resource name="jdbc/maakler_new" auth="Container" type="javax.sql.DataSource"
               maxActive="40" maxIdle="30" maxWait="15000"
               username="usr" password="pw" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://mydblocation.ee:3306/maakler_new"/>

  </GlobalNamingResources>

...

您在 server.xml 中缺少一个条目。这应该会有所帮助

http://examples.javacodegeeks.com/enterprise-java/tomcat/tomcat-connection-pool-configuration-example/

问题出在 Java 代码中。我正在从错误的上下文(根上下文)中寻找数据源。这是错误的:

Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("jdbc/maakler_new");

正确的方法是这样的:

Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/maakler_new");