Stop Grails from opening a connection to the database in a Controller method - database

I have a service that is communicating to another machine. Since it's a simple Controller method Grails automatically grabs a DB connection from the pool while my controller is communicating with the other server. I'd like to prevent it from doing that, and manually open up the database connection when I'm ready so that it doesn't suck up a connection during a long period like doing network calls. How do I prevent Grails from automatically grabbing a connection from the pool in a controller method?

When you create a controller it has the Transactional annotation on it, something like:
#Transactional(readOnly=true)
class FooController { ..
If you remove that annotation (and any method level annotations) then Grails will no longer connect to the database to start the transaction.
Open Session In View should not come into play since we use a lazy init approach for obtaining the connection with OSIV
Note my answer above assumes you are using a recent version of Grails (2.3.x or above)
Updated
For MongoDB you can disable automatically connection for all controllers by defining the following bean (which overrides the default) in grails-app/conf/spring/resources.groovy:
mongoPersistenceInterceptor(org.codehaus.groovy.grails.support.NullPersistentCon‌​textInterceptor)
However there is no way to disable on a per controller basis at the moment

Related

How to test Spring database down?

I have this SpringBoot server app using PostgreSQL database if it's up and sending error response if it's down. So my app is running regardless the database connection.
I would very much like to test it (jUnit / mockmvc).
My question is very simple, yet I did not find the answer online:
how does one simulate a database connection loss in SpringBoot?
If anyone wants, I can supply code (project is up at https://github.com/k-wasilewski/workshop/)
Have you thought of Testcontainers? You can spin up your docker image through a Junit test and make your spring boot use that as your database.
Since you use junit, you can start/stop this container at will.
This will generate a test which creates the condition you are looking for and write code as to what to expect when the database is down.
Here are some links to get started,
Testcontainers and Junit4 with Testcontainers quickstart - https://www.testcontainers.org/quickstart/junit_4_quickstart/
Spring boot documentation - Use Testcontainers for integration testing
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-testcontainers
Testcontainer github link example for springboot app
https://github.com/testcontainers/testcontainers-java/tree/master/examples/spring-boot
Testcontainer - Generic container javadoc. You can find methods for start/stop
container here. call from your Junit.
https://javadoc.io/static/org.testcontainers/testcontainers/1.12.4/org/testcontainers/containers/GenericContainer.html
You can implement your own Datasource based on DelegatingDataSource and then let it throw exceptions instead of delegating when ever you want to.
I've done this before by creating a Spring Boot test configuration class that created the DataSource and wrapped it in a Java proxy. The proxy simply passed method calls down to the underlying DataSource, until a certain flag was set. Once the flag was set, then any method called on the proxy would throw an exception without calling the underlying DataSource. Essentially, this allowed me to "bring the database down" or "up" simply by flipping the flag.

Database connection lifetime - Short lived vs per request

I have an MVC application, using StructureMap for IoC.
Within the application, data access is 95% via Entity Framework; however there are a few raw ADO.NET repositories that make use of an IDbConnection instance.
At present I register IDbConnection with the IoC container like this...
init.For<IDbConnection>()
.HybridHttpOrThreadLocalScoped()
.Use(() => this._connectionFactory.CreateConnection(config.ConnectionString));
init.Forward<IDbConnection, DbConnection>();
... and inject IDbConnection into the raw ADO.NET repositories where necessary.
However, at present I have _connectionFactory.CreateConnection() returning an OPEN connection with the intention of allowing StructureMap to close the connection at the end of the request.
Is it wise to do this?
Is it better to share a single open connection throughout the lifetime of the request, or open/close only where necessary and keep the connections short lived?

Zend prevent database connection on concrete action

Is this possible to prevent database connection while I requests concrete action in Zend Framework 2?
As Sam stated in a comment; if you do not wish to establish a connection to the database, then simply don't. If you do not have any code within your controller action that uses the database, then there won't be a database connection (provided that you are not doing funky stuff in a bootstrap method or similar).
If you are building a database connection in the standard way, then the actual connection will be lazily loaded, meaning that there won't be an actual connection before you try to use it.
In your comment you state that you believe the problem is caused by many database connections. I just want to clarify that there will only be one database connection per request (provided that you make use of the database).
If you have no code that calls a database, then your web server won't actually make a connection to your database. Either way, if you have 150+ images per page, then that would be a bigger concern and is probably the root cause for slow page loads. Perhaps consider pagination or if you do not display the pictures in their full sizes, then avoid scaling them in HTML as you would then be sending lots of unnecessary data from your web server to your visitors. You could resize the pictures in PHP when they are added, for instance. After that, you could even consider using a Content Delivery Network (CDN), but that is a different discussion...

Initialize Database connection in Jersey REST webapp

I want to make database queries in my Jersey REST webapp. The ideal situation would be to find a way where the database connection is initialised once at the first app run. Afterwards I only get the instance of DAOFactory object in my REST class and make the queries in the methods. I am using mysql connector. Is there a way to find a way to do it in Jersey? In JSF it was possible - I just used an application-scoped bean when I run the code. Moreover it would be good if I could access the ServletContext object inside this method cause I would like to use it's getResourceAsStream() method to read the database connection parameters from WEB-INF/dao.properties file. But the 'only once per app initialisation' is the crucial part here.

Spring + Hibernate with transactions in multithreading environment

I have a simple application that fetches some data from ONE table on db (MySQL 5.1) via Hibernate and display the content. The main framework used is Spring 3.0. The query runs correctly in #Transactional(read-only) (+second cache level).
The problems come out running some concurrent tests with 20/30 requests against the same page. Some page-requests return 500 instead of 200. I suppose that is due to #Transactional doesn't manage multi-thread access (pls correct me if I am wrong).
In the controller I have something like this:
List<String> names = usersService.getUserNames(); // this executes query in #Transactional env
doSomething(names);
the logs say that "doSomething" threws some NullPointerException as there are not data in the list passed.
Is there a way to implement a multi-thread access manager with Spring+Hibernate that manages concurrent requests to db?
#Transactional is working perfectly fine in multithreaded applications. In fact, all web applications are multithreaded, and each spring bean singleton instance handles all requests. So the issue is not there.
When you get error 500, you should check the logs files. If nothing's there, make sure you haven't swallowed some exception.
You need to make sure that a separate database connection is allocated to every incoming request. Connections should be managed in a pool. The size of the database connection pool would determine (indirectly) how many requests your application can server simultaneously.

Resources