Connector/J extension points – lifecycle interceptors
This is the first of a handful of posts to augment the presentations I gave at Java One and Silicon Valley Code Camp earlier this month. It seems I significantly overestimated how much content I could effectively deliver in the time allotted, and left a few of my major points untouched. These blog posts will try to rectify that.
The first major area I failed to cover in depth was really “Extension Points”, starting from slide #56. There are four major extension points in Connector/J:
- Lifecycle Interceptors
- Statement Interceptors
- Exception Interceptors
- Loadbalancing Strategies
We’ll look at the first in this post.
Connection lifecycle events can be useful for instrumenting or debugging application database behavior, without changing application code. In Connector/J, you can intercept the following lifecycle events by implementing com.mysql.jdbc.ConnectionLifecycleInterceptor:
- Connection creation (via the init() method)
- Transaction start/end (via transactionBegun() and transactionCompleted() methods)
- Connection object destruction (via destroy() method)
So, how might this be useful? In the demo code provided, I implemented code that prints the stack trace when Connection.rollback() is called. Perhaps you are trying to understand where rollbacks are coming from in your application – the demo code lets you do just that. The steps are fully illustrated in the demo code:
- Create a lifecycle interceptor that implements com.mysql.jdbc.ConnectionLifecycleInterceptor.
- Add logging in the rollback() method to track whatever you require.
- Start the application and list the fully-qualified class name of the lifecycle interceptor you created in step #1 as the value for property, “connectionLifecycleInterceptors”. In the demo code, this is found in demo.connectorj.LifecycleInterceptorExample at line 23:
What other lifecycle events might you be interested in tracking? Well, you might be interested in tracking the time between transaction start and end times. You might be interested to know how many times setAutoCommit() is called. It’s convenient that you can do all of this without modifying application code.