多数据源问题很常见,例如读写分离数据库配置。
原来的项目出现了新需求,局方要求新增某服务器用以提供某代码,涉及到多数据源的问题。
研究成果如下:
1、首先配置多个datasource
<bean id="datasource" class="org.apache.commons.dbcp.basicdatasource"> <property name="driverclassname" value="net.sourceforge.jtds.jdbc.driver"> </property> <property name="url" value="jdbc:jtds:sqlserver://10.82.81.51:1433;databasename=standards"> </property> <property name="username" value="youguess"></property> <property name="password" value="youguess"></property> </bean> <bean id="datasource2" class="org.apache.commons.dbcp.basicdatasource"> <property name="driverclassname" value="net.sourceforge.jtds.jdbc.driver"> </property> <property name="url" value="jdbc:jtds:sqlserver://10.82.81.52:1433;databasename=standards"> </property> <property name="username" value="youguess"></property> <property name="password" value="youguess"></property> </bean>
2、写一个dynamicdatasource类继承abstractroutingdatasource,并实现determinecurrentlookupkey方法
package com.standard.core.util; import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource; public class dynamicdatasource extends abstractroutingdatasource { @override protected object determinecurrentlookupkey() { return customercontextholder.getcustomertype(); } }
3、利用threadlocal解决线程安全问题
package com.standard.core.util; public class customercontextholder { public static final string data_source_a = "datasource"; public static final string data_source_b = "datasource2"; private static final threadlocal<string> contextholder = new threadlocal<string>(); public static void setcustomertype(string customertype) { contextholder.set(customertype); } public static string getcustomertype() { return contextholder.get(); } public static void clearcustomertype() { contextholder.remove(); } }
4、数据源配置
<bean id="dynamicdatasource" class="com.standard.core.util.dynamicdatasource" > <property name="targetdatasources"> <map key-type="java.lang.string"> <entry value-ref="datasource" key="datasource"></entry> <entry value-ref="datasource2" key="datasource2"></entry> </map> </property> <property name="defaulttargetdatasource" ref="datasource" > </property> </bean>
5、在daoimpl中切换数据源
搞定!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
第三次学JAVA再学不好就吃翔(part88)--ArrayList嵌套ArrayList
使用ffmpeg视频切片并加密和视频AES-128加密后播放
JAVA程序设计:最长重复子串(LeetCode:1044)
LiveGBS国标GB/T28181云端录像分布式录像存储自动清理时移回看录像下载播放
网友评论