1

I would like to use a MySQL Connection Pool with a Jersey REST service.

For performance reasons I don't want to create single MySQL connections each time a Jersey resource method is called. Instead I would like to create a ConnectionPool at startup-time of the server and then borrow and return connections when the service resource methods are executed.

Where would be the best place to put the initialization of the ConnectionPool within the Jersey REST framework?

tombo_189
  • 384
  • 5
  • 22
  • How do You run Jersey service, WITHOUT any server / container? Do You use Tomcat, Jetty, etc? – Jacek Cz Sep 15 '15 at 15:45
  • I plan to use Tomcat, currently for development purposes in Eclipse. – tombo_189 Sep 15 '15 at 19:05
  • REST hav not much to do with connection pool, but type of server is important. Every server has his own method. Framework has small built-in http server? I know nothing about him. – Jacek Cz Sep 15 '15 at 19:18

1 Answers1

0

Create a class and implement the ServletContextListener interface.

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");   
}
}

Put it in the deployment descriptor.

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

For more details check this link

  • I agree this should be the place to put it in the server. For an example of how to implement the pool in tomcat see [here](http://examples.javacodegeeks.com/enterprise-java/tomcat/tomcat-connection-pool-configuration-example/) – lrnzcig Sep 16 '15 at 10:10
  • After some googling a found in the [jersey documentation](https://jersey.java.net/documentation/latest/deployment.html) the `ResourceConfig` class which can be extended and deployed in order to setup the serivce. Do you think this would be a better approach than using the general `ServletContextListener` ? Both approaches do fire at service startup time. – tombo_189 Sep 18 '15 at 06:29
  • @tombo_189 the difference is that in the server provider you can also close connection pool at shutdown. BTW, I had not realized this question is probably a duplicate of [this one](http://stackoverflow.com/questions/12875682/initialize-database-on-jersey-webapp-startup). Please consider removing it. – lrnzcig Sep 25 '15 at 17:21