2015-09-15 46 views
1

我想使用帶有Jersey REST服務的MySQL連接池。在Jersey REST服務中初始化MySQL連接池的位置?

由於性能方面的原因,我不想在每次調用Jersey資源方法時創建單個MySQL連接。相反,我想在服務器啓動時創建一個ConnectionPool,然後在執行服務資源方法時借用並返回連接。

哪裏可以將Jersey的REST框架中的ConnectionPool初始化的最佳位置?

+0

你怎麼跑澤西服務,沒有任何服務器/容器?你使用Tomcat,Jetty等? –

+0

我打算使用Tomcat,目前在Eclipse中用於開發目的。 –

+0

REST與連接池無關,但服務器的類型很重要。每個服務器都有自己的方法。框架有小內置http服務器?我對他一無所知。 –

回答

0

創建一個類並實現ServletContextListener接口。

package com.example.listener; 
import javax.servlet.ServletContextEvent; 
import javax.servlet.ServletContextListener; 

public class MyAppServletContextListener 
       implements ServletContextListener{ 

@Override 
public void contextDestroyed(ServletContextEvent arg0) { 
    System.out.println("ServletContextListener destroyed"); 
} 

    //Run this before web application is started 
@Override 
public void contextInitialized(ServletContextEvent arg0) { 
    System.out.println("ServletContextListener started"); 
} 
} 

將其放入部署描述符中。

<web-app ...> 
    <listener> 
<listener-class> 
     com.example.listener.MyAppServletContextListener 
    </listener-class> 
</listener> 
</web-app> 

有關詳情,請這個link

+0

我同意這應該是把它放在服務器中的地方。有關如何在tomcat中實現池的示例,請參閱[here](http://examples.javacodegeeks.com/enterprise-java/tomcat/tomcat-connection-pool-configuration-example/) – lrnzcig

+0

經過一些Google搜索後發現[球衣文檔](https://jersey.java.net/documentation/latest/deployment.html)ResourceConfig類,可以擴展和部署以設置服務。你認爲這比使用通用的'ServletContextListener'更好嗎?這兩種方法在服務啓動時都會觸發。 –

+0

@ tombo_189所不同的是,在服務器提供者中,您也可以在關閉時關閉連接池。順便說一句,我沒有意識到這個問題可能是[這一個]的副本(http://stackoverflow.com/questions/12875682/initialize-database-on-jersey-webapp-startup)。請考慮刪除它。 – lrnzcig

相關問題