攔截器中操作數據庫


做了個小項目,當初設計的是只有一個模塊的用戶行為被記錄,其他不用記錄,昨天突然說,要用戶在整個系統的行為都要被記錄.
很懵逼,如果把用戶行為的記錄放在各個模塊,可以很精確的記錄,但是各個模塊都要有更改.如果使用攔截器,只能很粗粒度的記錄用戶的行為.
下面是使用攔截器的一些關鍵代碼,主要是記錄一下在攔截器中操作數據庫得方法.
參考文章,文章介紹很詳細,需要完整介紹的可以直接去看看.

  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),具體更改方法百度一下,你就知道.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM