拦截器中操作数据库

做了个小项目,当初设计的是只有一个模块的用户行为被记录,其他不用记录,昨天突然说,要用户在整个系统的行为都要被记录.
很懵逼,如果把用户行为的记录放在各个模块,可以很精确的记录,但是各个模块都要有更改.如果使用拦截器,只能很粗粒度的记录用户的行为.
下面是使用拦截器的一些关键代码,主要是记录一下在拦截器中操作数据库得方法.
参考文章,文章介绍很详细,需要完整介绍的可以直接去看看.

  1. 拦截器
/**
 * xxxxxxxxxxx
 * @author xxxxxxxx
 * @date 2018/9/6 10:38
 */
public class UserBehaviorInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e)
			throws Exception {

		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object arg2) throws Exception {
        //1. 创建用户行为日志实例
        //---------------------------------
       
        
		 //2, 获取相关数据,并保存在用户行为日志实例中
		
        
		//3. 获取DAO
        //-----------------------此处比较重要,下面有说明--------------------
		//4. 把日志信息保存到数据库中
        //--------------------

		return true;
	}

	//获取dao,拦截器中只能通过webapplicationcontextutils获取spring boot中的bean.
	private <T> T  getDao(Class<T> t,HttpServletRequest request){
		 BeanFactory beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		 return beanFactory.getBean(t);

	}
}

备注:在拦截器中获取spring boot中的bean需要通过webapplicationcontextutils获取

  1. 把拦截器添加到spring boot容器中
@Configuration
public class UserBehaviorInterceptorConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addInterceptor(new UserBehaviorInterceptor()).addPathPatterns("/**");
    }
}

数据库链接空闲时间和连接池

之前做的一个管理网站,开着服务一天,最后访问的时候,会偶尔出现错误,刷新一下有好了,后台提示的是

com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 31,998,324 milliseconds ago.  The last packet sent successfully to the server was 31,998,324 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
	at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:590) ~[mysql-connector-java-6.0.6.jar:6.0.6]
.....

网上说,是由于数据库在超出wait_timeout后,会收回链接,单数数据库连接池还持有者链接引用,这样就会造成,从数据库中去链接后,出现上面的异常.别人建议是:

  1. 如果不是系统性能出现问题,尽量不使用连接池
  2. 使用连接池,最好更改数据库的链接空闲时间(wait_timeout),具体更改方法百度一下,你就知道.
原文地址:https://www.cnblogs.com/donfaquir/p/9600653.html