One connection to MySql database for REST service

I am developing an Android application that receives and writes data to a database via a REST service. I am setting up a REST service with Jersey and Tomcat in Java.

I created one database connection when the REST service starts. All android clients now share the same database connection. Now I just want to know how good it is to use a single database connection in my scenario. multiple concurrent requests?

Please suggest ....

Update When I test the following scenario, it gives different results. I just configured a simple REST server with tomcat using only jersey with Get annotation, inside this annotation I am writing code to get the name of the employee whose ID is 300 using the database connection that was established when REST was started. So when I writehttp://192.168.15.9:8080/Rest/rest/person/sample

in my web browser, I got the employee name ... Then I created a batch file to open the url in 100 tabs, I executed the batch file. At the same time, I open the url from my virtual machine and get the employee name without delay. Also, the employee's name is displayed on 100 tabs after 20 seconds. If a single database connection cannot be used for concurrent users, then why am I giving a quick answer ?? Can someone please explain?

+3


source to share


1 answer


No, one database connection should not be used for concurrent requests. You have to create a connection pool (basically a set of reusable connections), optionally accept a connection from the pool and then release it to the pool.

Don't do it yourself!



Since you have Tomcat, you can set up a JDBC datasource and then use JNDI to get a link to that datasource. The data source will provide you with the connections, without having to create the connections yourself. Tomcat will bundle (activate, maintain and dispose of) connections under the hood.
Alternatively, you can use a custom connection pool such as c3p0 , but I highly recommend you use the tools your server provides.

If for some reason you need to deploy your product in a matter of minutes (so you don't have time to set up the data source), then you are better off opening and closing connections for every request, which is wasteful, rather than sharing a single connection for all requests.

+4


source







All Articles