threadlocal使用案例

threadlocal使用案例

ID:5349054

大小:690.61 KB

页数:8页

时间:2017-12-08

threadlocal使用案例_第1页
threadlocal使用案例_第2页
threadlocal使用案例_第3页
threadlocal使用案例_第4页
threadlocal使用案例_第5页
资源描述:

《threadlocal使用案例》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、ThreadLocal使用案例用户提出一个需求:当修改产品价格的时候,需要记录操作日志,什么时候做了什么事情。想必这个案例,只要是做过应用系统的小伙伴们,都应该遇到过吧?无外乎数据库里就两张表:product与log,用两条SQL语句应该可以解决问题:updateproductsetprice=?whereid=?insertintolog(created,description)values(?,?)But!要确保这两条SQL语句必须在同一个事务里进行提交,否则有可能update提交了,但insert却没有提交。如果这样的事情真的发生了,我们肯

2、定会被用户指着鼻子狂骂:“为什么产品价格改了,却看不到什么时候改的呢?”。聪明的我在接到这个需求以后,是这样做的:首先,我写一个DBUtil的工具类,封装了数据库的常用操作:publicclassDBUtil{//数据库配置privatestaticfinalStringdriver="com.mysql.jdbc.Driver";privatestaticfinalStringurl="jdbc:mysql://localhost:3306/demo";privatestaticfinalStringusername="root";privat

3、estaticfinalStringpassword="root";//定义一个数据库连接privatestaticConnectionconn=null;//获取连接publicstaticConnectiongetConnection(){try{Class.forName(driver);conn=DriverManager.getConnection(url,username,password);}catch(Exceptione){e.printStackTrace();}returnconn;}//关闭连接publicstaticvo

4、idcloseConnection(){try{if(conn!=null){1/8conn.close();}}catch(Exceptione){e.printStackTrace();}}}里面搞了一个static的Connection,这下子数据库连接就好操作了,牛逼吧!然后,我定义了一个接口,用于给逻辑层来调用:publicinterfaceProductService{voidupdateProductPrice(longproductId,intprice);}根据用户提出的需求,我想这个接口完全够用了。根据productId去更新

5、对应Product的price,然后再插入一条数据到log表中。其实业务逻辑也不太复杂,于是我快速地完成了ProductService接口的实现类:publicclassProductServiceImplimplementsProductService{privatestaticfinalStringUPDATE_PRODUCT_SQL="updateproductsetprice=?whereid=?";privatestaticfinalStringINSERT_LOG_SQL="insertintolog(created,descript

6、ion)values(?,?)";publicvoidupdateProductPrice(longproductId,intprice){try{//获取连接Connectionconn=DBUtil.getConnection();conn.setAutoCommit(false);//关闭自动提交事务(开启事务)//执行操作updateProduct(conn,UPDATE_PRODUCT_SQL,productId,price);//更新产品insertLog(conn,INSERT_LOG_SQL,"Createproduct.");/

7、/插入日志//提交事务conn.commit();}catch(Exceptione){e.printStackTrace();}finally{2/8//关闭连接DBUtil.closeConnection();}}privatevoidupdateProduct(Connectionconn,StringupdateProductSQL,longproductId,intproductPrice)throwsException{PreparedStatementpstmt=conn.prepareStatement(updateProduct

8、SQL);pstmt.setInt(1,productPrice);pstmt.setLong(2,productId);introws

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。