服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring配置多数据源切换

Spring配置多数据源切换

2021-06-27 17:14丶Melody Java教程

今天小编就为大家分享一篇关于Spring配置多数据源切换,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

多数据源切换

db.properties

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#mysql
jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc:mysql://localhost:3306/test?autoreconnect=true&characterencoding=utf-8
jdbc.username=root
jdbc.password=admin
#定义初始连接数
initialsize=0
#定义最大连接数
maxactive=1000
#定义最大空闲
maxidle=20
#定义最小空闲
minidle=1
#定义最长等待时间
maxwait=60000
#mysql
# driverclassname 根据url自动识别 这一项可配可不配,如果不配置druid会根据url自动识别dbtype,然后选择相应的driverclassname
jdbc.driver1=com.mysql.jdbc.driver
jdbc.url1=jdbc:mysql://localhost:3306/test1?allowmultiqueries=true&autoreconnect=true&characterencoding=utf-8
jdbc.username1=root
jdbc.password1=admin
# 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getconnection时
initialsize1=0
# 最大连接池数量
maxactive1=1000
#定义最小空闲
minidle1=1
# 获取连接时最大等待时间,单位毫秒。配置了maxwait之后,
# 缺省启用公平锁,并发效率会有所下降,
# 如果需要可以通过配置useunfairlock属性为true使用非公平锁。
maxwait1=60000
# druid 监控
# 属性类型是字符串,通过别名的方式配置扩展插件,
# 常用的插件有:
# 监控统计用的filter:stat
# 日志用的filter:log4j
# 防御sql注入的filter:wall
filters1=stat,log4j
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timebetweenevictionrunsmillis1=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minevictableidletimemillis1=300000
# 建议配置为true,不影响性能,并且保证安全性。
# 申请连接的时候检测,如果空闲时间大于
# timebetweenevictionrunsmillis,
# 执行validationquery检测连接是否有效。
testwhileidle1=true
# 申请连接时执行validationquery检测连接是否有效,做了这个配置会降低性能。
testonborrow1=false
# 归还连接时执行validationquery检测连接是否有效,做了这个配置会降低性能
testonreturn1=false
# 是否缓存preparedstatement,也就是pscache。
# pscache对支持游标的数据库性能提升巨大,比如说oracle。
# 在mysql5.5以下的版本中没有pscache功能,建议关闭掉。
# 作者在5.5版本中使用pscache,通过监控界面发现pscache有缓存命中率记录,
# 该应该是支持pscache。
poolpreparedstatements1=false
# 要启用pscache,必须配置大于0,当大于0时,
# poolpreparedstatements自动触发修改为true
# 在druid中,不会存在oracle下pscache占用内存过多的问题,
# 可以把这个数值配置大一些,比如说100
maxopenpreparedstatements1=-1

applicationcontext.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:websocket="http://www.springframework.org/schema/websocket"
  xsi:schemalocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/websocket
    http://www.springframework.org/schema/websocket/spring-websocket.xsd">
  <!-- spring使用注解 配置扫描  com.ys下的扫描 但是在springmvc里边已经扫描一次了
   这时就要加上属性 use-default-filters="true"  这个属性就是使用默认的扫描
   默认就扫描com.ys下所有 设置为false 在下边配置需要扫描的部分-->
   <!-- 现在的配置就只会扫描带@service@repository注解的类 -->
  <context:component-scan base-package="com" use-default-filters="false">
  <!-- org.springframework.stereotype.service就是注解@service 这个注解使用在service里 所以就是扫描service包
  org.springframework.stereotype.repository  repository仓库-->
    <context:include-filter type="annotation" expression="org.springframework.stereotype.controller"/>
    <context:include-filter type="annotation" expression="org.springframework.beans.factory.annotation.autowired"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.service"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.repository"/>
  </context:component-scan>
  <!-- 读取properties文件 -->
  <bean id="propertyconfigurer" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer">
    <property name="locations">
      <list>
        <value>classpath:db.properties</value>
      </list>
    </property>
  </bean>
  <!-- 配置连接池数据源  文档搜索basicdatasource -->
  <bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close">
    <!-- results in a setdriverclassname(string) call -->
    <property name="driverclassname" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <!-- 初始化连接大小 -->
    <property name="initialsize" value="${initialsize}"></property>
    <!-- 连接池最大数量 -->
    <property name="maxactive" value="${maxactive}"></property>
    <!-- 连接池最大空闲 -->
    <property name="maxidle" value="${maxidle}"></property>
    <!-- 连接池最小空闲 -->
    <property name="minidle" value="${minidle}"></property>
    <!-- 获取连接最大等待时间 -->
    <property name="maxwait" value="${maxwait}"></property>
  </bean>
  <bean id="datasource1" class="com.alibaba.druid.pool.druiddatasource" destroy-method="close">
    <property name="url" value="${jdbc.url1}" />
    <property name="username" value="${jdbc.username1}" />
    <property name="password" value="${jdbc.password1}" />
    <property name="driverclassname" value="${jdbc.driver1}" />
    <!-- 初始化连接大小 -->
    <property name="initialsize" value="${initialsize1}"/>
    <!-- 最小空闲 -->
    <property name="minidle" value="${minidle1}" />
    <!-- 最大连接池数量 -->
    <property name="maxactive" value="${maxactive1}" />
    <!-- 获取连接最大等待时间 -->
    <property name="maxwait" value="${maxwait1}"/>
    <!-- 监控统计用的filter:stat  日志用的filter:log4j 防御sql注入的filter:wall -->
    <property name="filters" value="${filters1}" />
    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    <property name="timebetweenevictionrunsmillis" value="${timebetweenevictionrunsmillis1}" />
    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    <property name="minevictableidletimemillis" value="${minevictableidletimemillis1}" />
    <!-- 建议配置为true,不影响性能,并且保证安全性。 申请连接的时候检测 -->
    <property name="testwhileidle" value="${testwhileidle1}"/>
    <!-- 申请连接时执行validationquery检测连接是否有效,做了这个配置会降低性能。 -->
    <property name="testonborrow" value="${testonborrow1}"/>
    <!-- 归还连接时执行validationquery检测连接是否有效,做了这个配置会降低性能 -->
    <property name="testonreturn" value="false" />
    <!-- 是否缓存preparedstatement,也就是pscache 适用支持游标的数据库 如oracle -->
    <property name="poolpreparedstatements" value="${poolpreparedstatements1}"/>
    <!-- 要启用pscache,必须配置大于0,当大于0时 poolpreparedstatements自动触发修改为true。 -->
    <property name="maxopenpreparedstatements" value="${maxopenpreparedstatements1}"/>
    <!-- 定义监控日志输出间隔 -->
    <property name="timebetweenlogstatsmillis" value="60000"/>
    <!--<property name="statlogger" ref ="statloggerb"/> -->
    <!-- 若需要mybatis的批量sql需配置   不配置则报错:nested exception is java.sql.sqlexception: sql injection violation, multi-statement not allow-->
    <property name="proxyfilters" ref="wall-filter"/>
  </bean>
  <!-- 若需要mybatis的批量sql需配置 -->
  <bean id="wall-filter" class="com.alibaba.druid.wall.wallfilter">
    <property name="config" ref="wall-config" />
  </bean>
  <bean id="wall-config" class="com.alibaba.druid.wall.wallconfig">
    <property name="multistatementallow" value="true" />
  </bean>
  <!-- 多数据源配置 -->
  <bean id="multipledatasource" class="com.ys.dbconfig.multipledatasource">
    <!-- 默认数据源 -->
    <property name="defaulttargetdatasource" ref="datasource" />
    <property name="targetdatasources">
      <map key-type="java.lang.string">
        <entry key="datasource" value-ref="datasource"/>
        <entry key="datasource1" value-ref="datasource1"/>
      </map>
    </property>
  </bean>
  <!-- 配置 sqlsessionfactory -->
  <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
    <!-- 数据库连接池 -->
    <property name="datasource" ref="multipledatasource"/>
    <property name="configlocation" value="classpath:mybatis.cfg.xml"/>
    <!-- 加载mybatis全局配置文件 -->
    <property name="mapperlocations" value="classpath:com/ys/mapper/*.xml"/>
  </bean>
  <!-- 扫描的dao包(映射文件) 本身应该在mybatis里 现在交给spring -->
  <bean id="mapperscannerconfigurer" class="org.mybatis.spring.mapper.mapperscannerconfigurer">
    <property name="basepackage" value="com.ys.dao"/>
  </bean>
<!-- 事务配置 --> 
  <!-- 配置事务管理 -->
  <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
    <property name="datasource" ref="multipledatasource"></property>
  </bean>
  <!-- 开启注解事务 引用transactionmanager -->
  <tx:annotation-driven transaction-manager="transactionmanager"/>
</beans>

创建multipledatasource.java

?
1
2
3
4
5
6
7
8
package com.ys.dbconfig;
import org.springframework.jdbc.datasource.lookup.abstractroutingdatasource;
public class multipledatasource extends abstractroutingdatasource{
  @override
  protected object determinecurrentlookupkey() {
    return multipledatasourcehandler.getroutekey();
  }
}

创建multipledatasourcehandler.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.ys.dbconfig;
/**
*@ title multipledatasourcehandler.java
*@ description: 多数据源handler
*@ time 创建时间:2018年8月25日 上午10:52:12
**/
public class multipledatasourcehandler {
  private static threadlocal<string> routekey = new threadlocal<string>();
  /**
   * @title: getroutekey
   * @description: 获取当前线程的数据源路由的key
   * @param @return
   * @return string
   * @date createtime:2018年8月27日上午10:34:52
   */
  public static string getroutekey(){
    return routekey.get();
  }
  /**
   * @title: setroutekey
   * @description: 绑定当前线程数据源路由的key 使用完成后必须调用removeroutekey()方法删除
   * @param @param key
   * @return void
   * @date createtime:2018年8月27日上午10:35:03
   */
  public static void setroutekey(string key){
    routekey.set(key);
  }
  /**
   * @title: removeroutekey
   * @description: 删除与当前线程绑定的数据源路由的key
   * @return void
   * @date createtime:2018年8月27日上午10:35:31
   */
  public static void removeroutekey(){
    routekey.remove();
  }
}

切换数据源

?
1
multipledatasourcehandler.setroutekey(“datasource1”);

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/qq_36476972/article/details/82108755

延伸 · 阅读

精彩推荐