- 浏览: 34122 次
- 性别:
- 来自: 广州
最新评论
-
appache:
我问一下,MapGuide里面使用的账户验证机制如何能添加自己 ...
一个GIS项目开发(采用MapGuide)的简单总结(转载)
一、配置定义数据库连接属性
二、定义bean
<!-- 主数据库连接池 -->
<bean id="masterDataSource" parent="abstractDataSource">
<property name="url" value="${master.jdbc.url}"/>
<property name="username" value="${master.jdbc.username}"/>
<property name="password" value="${master.jdbc.password}"/>
</bean>
<!-- 从数据库连接池1 -->
<bean id="slave1DataSource" parent="abstractDataSource">
<property name="url" value="${slave1.jdbc.url}"/>
<property name="username" value="${slave1.jdbc.username}"/>
<property name="password" value="${slave1.jdbc.password}"/>
</bean>
<!-- 从数据库连接池2 -->
<bean id="slave2DataSource" parent="abstractDataSource">
<property name="url" value="${slave2.jdbc.url}"/>
<property name="username" value="${slave2.jdbc.username}"/>
<property name="password" value="${slave2.jdbc.password}"/>
</bean>
<!-- 从数据库连接池3 -->
<bean id="slave3DataSource" parent="abstractDataSource">
<property name="url" value="${slave3.jdbc.url}"/>
<property name="username" value="${slave3.jdbc.username}"/>
<property name="password" value="${slave3.jdbc.password}"/>
</bean>
<!-- 动态切换数据源 -->
<bean id="dynamicDataSource" class="com.common.datasource.DynamicDataSource">
<property name="writeDataSource" ref="masterDataSource"></property>
<property name="readDataSources">
<list>
<ref bean="slave1DataSource" />
<ref bean="slave2DataSource" />
<ref bean="slave3DataSource" />
</list>
</property>
<!--轮询方式-->
<property name="readDataSourcePollPattern" value="1" />
<property name="onlyWrite" value="true" />
</bean>
三、事务定义
<!-- 事务管理器 -->
<bean id="dynamicTransactionManager" class="com.common.datasource.DynamicDataSourceTransactionManager">
<property name="dataSource" ref="dynamicDataSource"/>
</bean>
<tx:annotation-driven transaction-manager="dynamicTransactionManager"/>
四、配置插件
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.common.datasource.DynamicPlugin" />
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
五、编写动态数据源类
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Long MAX_POOL = Long.MAX_VALUE;
private final Lock lock = new ReentrantLock();
private Object writeDataSource; //写数据源
private List<Object> readDataSources; //多个读数据源
private int readDataSourceSize; //读数据源个数
private int readDataSourcePollPattern = 0; //获取读数据源方式,0:随机,1:轮询
private AtomicLong counter = new AtomicLong(0);
private boolean onlyWrite=false;
@Override
public void afterPropertiesSet() {
if (this.writeDataSource == null) {
throw new IllegalArgumentException("Property 'writeDataSource' is required");
}
setDefaultTargetDataSource(writeDataSource);
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DynamicDataSourceGlobal.WRITE.name(), writeDataSource);
if (readDataSources != null) {
for (int i = 0; i < readDataSources.size(); i++) {
targetDataSources.put(DynamicDataSourceGlobal.READ.name() + i, readDataSources.get(i));
}
readDataSourceSize = readDataSources.size();
} else {
readDataSourceSize = 0;
}
setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
if (onlyWrite){
return DynamicDataSourceGlobal.WRITE.name();
}
DynamicDataSourceGlobal dynamicDataSourceGlobal = DynamicDataSourceHolder.getDataSource();
if (dynamicDataSourceGlobal == null || dynamicDataSourceGlobal == DynamicDataSourceGlobal.WRITE || readDataSourceSize <= 0) {
return DynamicDataSourceGlobal.WRITE.name();
}
//index表示选择第几个从数据库
int index;
if(readDataSourcePollPattern == 1) {
//轮询方式
long currValue = counter.incrementAndGet();
if((currValue + 1) >= MAX_POOL) {
try {
lock.lock();
if((currValue + 1) >= MAX_POOL) {
counter.set(0);
}
} finally {
lock.unlock();
}
}
index = (int) (currValue % readDataSourceSize);
} else {
//随机方式
index = ThreadLocalRandom.current().nextInt(0, readDataSourceSize);
}
return dynamicDataSourceGlobal.name() + index;
}
public void setWriteDataSource(Object writeDataSource) {
this.writeDataSource = writeDataSource;
}
public List<Object> getReadDataSources() {
return readDataSources;
}
public void setReadDataSources(List<Object> readDataSources) {
this.readDataSources = readDataSources;
}
public Object getWriteDataSource() {
return writeDataSource;
}
public int getReadDataSourceSize() {
return readDataSourceSize;
}
public void setReadDataSourceSize(int readDataSourceSize) {
this.readDataSourceSize = readDataSourceSize;
}
public int getReadDataSourcePollPattern() {
return readDataSourcePollPattern;
}
public void setReadDataSourcePollPattern(int readDataSourcePollPattern) {
this.readDataSourcePollPattern = readDataSourcePollPattern;
}
public boolean isOnlyWrite() {
return onlyWrite;
}
public void setOnlyWrite(boolean onlyWrite) {
this.onlyWrite = onlyWrite;
}
}
public class DynamicDataSourceHolder {
private static final ThreadLocal<DynamicDataSourceGlobal> holder = new ThreadLocal<DynamicDataSourceGlobal>();
private DynamicDataSourceHolder() {
//
}
public static void putDataSource(DynamicDataSourceGlobal dataSource) {
holder.set(dataSource);
}
public static DynamicDataSourceGlobal getDataSource() {
return holder.get();
}
public static void clearDataSource() {
holder.remove();
}
}
public class DynamicDataSourceTransactionManager extends DataSourceTransactionManager {
/**
* 只读事务到读库,读写事务到写库
*
* @param transaction
* @param definition
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
//设置数据源
boolean readOnly = definition.isReadOnly();
if (readOnly) {
DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.READ);
} else {
DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
}
super.doBegin(transaction, definition);
}
/**
* 清理本地线程的数据源
*
* @param transaction
*/
@Override
protected void doCleanupAfterCompletion(Object transaction) {
super.doCleanupAfterCompletion(transaction);
DynamicDataSourceHolder.clearDataSource();
}
}
/**
* Desc: Mybatis动态数据库切换插件
*/
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {
MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class})})
public class DynamicPlugin implements Interceptor {
protected static final Logger logger = LoggerFactory.getLogger(DynamicPlugin.class);
private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";
private static final Map<String, DynamicDataSourceGlobal> cacheMap = new ConcurrentHashMap<>();
@Override
public Object intercept(Invocation invocation) throws Throwable {
boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
if (!synchronizationActive) {
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
DynamicDataSourceGlobal dynamicDataSourceGlobal;
if ((dynamicDataSourceGlobal = cacheMap.get(ms.getId())) == null) {
//读方法
if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
//!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
} else {
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
if (sql.matches(REGEX)) {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
} else {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.READ;
}
}
} else {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
}
logger.warn("设置方法[{}] use [{}] Strategy, SqlCommandType [{}]..", ms.getId(), dynamicDataSourceGlobal.name(), ms.getSqlCommandType().name());
cacheMap.put(ms.getId(), dynamicDataSourceGlobal);
}
DynamicDataSourceHolder.putDataSource(dynamicDataSourceGlobal);
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
//
}
二、定义bean
<!-- 主数据库连接池 -->
<bean id="masterDataSource" parent="abstractDataSource">
<property name="url" value="${master.jdbc.url}"/>
<property name="username" value="${master.jdbc.username}"/>
<property name="password" value="${master.jdbc.password}"/>
</bean>
<!-- 从数据库连接池1 -->
<bean id="slave1DataSource" parent="abstractDataSource">
<property name="url" value="${slave1.jdbc.url}"/>
<property name="username" value="${slave1.jdbc.username}"/>
<property name="password" value="${slave1.jdbc.password}"/>
</bean>
<!-- 从数据库连接池2 -->
<bean id="slave2DataSource" parent="abstractDataSource">
<property name="url" value="${slave2.jdbc.url}"/>
<property name="username" value="${slave2.jdbc.username}"/>
<property name="password" value="${slave2.jdbc.password}"/>
</bean>
<!-- 从数据库连接池3 -->
<bean id="slave3DataSource" parent="abstractDataSource">
<property name="url" value="${slave3.jdbc.url}"/>
<property name="username" value="${slave3.jdbc.username}"/>
<property name="password" value="${slave3.jdbc.password}"/>
</bean>
<!-- 动态切换数据源 -->
<bean id="dynamicDataSource" class="com.common.datasource.DynamicDataSource">
<property name="writeDataSource" ref="masterDataSource"></property>
<property name="readDataSources">
<list>
<ref bean="slave1DataSource" />
<ref bean="slave2DataSource" />
<ref bean="slave3DataSource" />
</list>
</property>
<!--轮询方式-->
<property name="readDataSourcePollPattern" value="1" />
<property name="onlyWrite" value="true" />
</bean>
三、事务定义
<!-- 事务管理器 -->
<bean id="dynamicTransactionManager" class="com.common.datasource.DynamicDataSourceTransactionManager">
<property name="dataSource" ref="dynamicDataSource"/>
</bean>
<tx:annotation-driven transaction-manager="dynamicTransactionManager"/>
四、配置插件
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.common.datasource.DynamicPlugin" />
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
五、编写动态数据源类
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Long MAX_POOL = Long.MAX_VALUE;
private final Lock lock = new ReentrantLock();
private Object writeDataSource; //写数据源
private List<Object> readDataSources; //多个读数据源
private int readDataSourceSize; //读数据源个数
private int readDataSourcePollPattern = 0; //获取读数据源方式,0:随机,1:轮询
private AtomicLong counter = new AtomicLong(0);
private boolean onlyWrite=false;
@Override
public void afterPropertiesSet() {
if (this.writeDataSource == null) {
throw new IllegalArgumentException("Property 'writeDataSource' is required");
}
setDefaultTargetDataSource(writeDataSource);
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DynamicDataSourceGlobal.WRITE.name(), writeDataSource);
if (readDataSources != null) {
for (int i = 0; i < readDataSources.size(); i++) {
targetDataSources.put(DynamicDataSourceGlobal.READ.name() + i, readDataSources.get(i));
}
readDataSourceSize = readDataSources.size();
} else {
readDataSourceSize = 0;
}
setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
if (onlyWrite){
return DynamicDataSourceGlobal.WRITE.name();
}
DynamicDataSourceGlobal dynamicDataSourceGlobal = DynamicDataSourceHolder.getDataSource();
if (dynamicDataSourceGlobal == null || dynamicDataSourceGlobal == DynamicDataSourceGlobal.WRITE || readDataSourceSize <= 0) {
return DynamicDataSourceGlobal.WRITE.name();
}
//index表示选择第几个从数据库
int index;
if(readDataSourcePollPattern == 1) {
//轮询方式
long currValue = counter.incrementAndGet();
if((currValue + 1) >= MAX_POOL) {
try {
lock.lock();
if((currValue + 1) >= MAX_POOL) {
counter.set(0);
}
} finally {
lock.unlock();
}
}
index = (int) (currValue % readDataSourceSize);
} else {
//随机方式
index = ThreadLocalRandom.current().nextInt(0, readDataSourceSize);
}
return dynamicDataSourceGlobal.name() + index;
}
public void setWriteDataSource(Object writeDataSource) {
this.writeDataSource = writeDataSource;
}
public List<Object> getReadDataSources() {
return readDataSources;
}
public void setReadDataSources(List<Object> readDataSources) {
this.readDataSources = readDataSources;
}
public Object getWriteDataSource() {
return writeDataSource;
}
public int getReadDataSourceSize() {
return readDataSourceSize;
}
public void setReadDataSourceSize(int readDataSourceSize) {
this.readDataSourceSize = readDataSourceSize;
}
public int getReadDataSourcePollPattern() {
return readDataSourcePollPattern;
}
public void setReadDataSourcePollPattern(int readDataSourcePollPattern) {
this.readDataSourcePollPattern = readDataSourcePollPattern;
}
public boolean isOnlyWrite() {
return onlyWrite;
}
public void setOnlyWrite(boolean onlyWrite) {
this.onlyWrite = onlyWrite;
}
}
public class DynamicDataSourceHolder {
private static final ThreadLocal<DynamicDataSourceGlobal> holder = new ThreadLocal<DynamicDataSourceGlobal>();
private DynamicDataSourceHolder() {
//
}
public static void putDataSource(DynamicDataSourceGlobal dataSource) {
holder.set(dataSource);
}
public static DynamicDataSourceGlobal getDataSource() {
return holder.get();
}
public static void clearDataSource() {
holder.remove();
}
}
public class DynamicDataSourceTransactionManager extends DataSourceTransactionManager {
/**
* 只读事务到读库,读写事务到写库
*
* @param transaction
* @param definition
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
//设置数据源
boolean readOnly = definition.isReadOnly();
if (readOnly) {
DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.READ);
} else {
DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
}
super.doBegin(transaction, definition);
}
/**
* 清理本地线程的数据源
*
* @param transaction
*/
@Override
protected void doCleanupAfterCompletion(Object transaction) {
super.doCleanupAfterCompletion(transaction);
DynamicDataSourceHolder.clearDataSource();
}
}
/**
* Desc: Mybatis动态数据库切换插件
*/
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {
MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class})})
public class DynamicPlugin implements Interceptor {
protected static final Logger logger = LoggerFactory.getLogger(DynamicPlugin.class);
private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";
private static final Map<String, DynamicDataSourceGlobal> cacheMap = new ConcurrentHashMap<>();
@Override
public Object intercept(Invocation invocation) throws Throwable {
boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
if (!synchronizationActive) {
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
DynamicDataSourceGlobal dynamicDataSourceGlobal;
if ((dynamicDataSourceGlobal = cacheMap.get(ms.getId())) == null) {
//读方法
if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
//!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
} else {
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
if (sql.matches(REGEX)) {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
} else {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.READ;
}
}
} else {
dynamicDataSourceGlobal = DynamicDataSourceGlobal.WRITE;
}
logger.warn("设置方法[{}] use [{}] Strategy, SqlCommandType [{}]..", ms.getId(), dynamicDataSourceGlobal.name(), ms.getSqlCommandType().name());
cacheMap.put(ms.getId(), dynamicDataSourceGlobal);
}
DynamicDataSourceHolder.putDataSource(dynamicDataSourceGlobal);
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
//
}
相关推荐
spring +springboot+mybatis+maven 读写分离,数据库采用mysql, 采用springboot 采用项目框架搭建,继承spring 中的AbstractRoutingDataSource,实现 determineCurrentLookupKey 进行数据源的动态切换,采用Spring ...
springBoot+mybatis+AOP实现读写分离,在代码层面直接实现,无需任何插件,简单易懂,非常适合作为解决数据库并发大的解决方案
springboot+mybatis+mysql实现读写分离 先在建好mysql主从数据库的配置,然后在代码中根据读写分离或强制读取master数据库中的数据 mysql数据库设置主从,参考: ...
spring+springmvc+mybatis+maven+mysql 数据库读写分离
springboot+mybatis+druid+redis实现数据库读写分离和缓存
spring+springmvc+mybatis的整合以及数据库读写分离的测试
本demo 实现了 spring+mysql+mybatis+springMVC 读写分离 希望对有需要的朋友有帮助如果大家有什么好的意见可以提 互相学习 觉得有用多多点赞哈哈哈!
sprngmvc+mybatis插件实现的读写分离案例,一写多读,有相关数据库文件及完整的代码,可部署运行。
spring+mybatis 数据路由JAR包,实现事物级控制,读写库多次分离,非cloud 配置中心。
Spring AOP + SpringMVC +Mybatis做动态数据源,实现读写分离Spring AOP + SpringMVC +Mybatis做动态数据源,实现读写分离Spring AOP + SpringMVC +Mybatis做动态数据源,实现读写分离
Mybatis读写分离,支持n多的从库,简单的负载均衡。数据库是mysql,采用druid连接池。 读写分离采用插件的形式实现的,优点是不需要写源注解,不需要写分开的Mapper.xml。 如果只有主库的话,那么会创建两个地址相同...
项目集成spring+springmvc+mybatis三层框架模型; 项目实现读写数据库分类。 项目包中包含数据库表结构。 添加数据加密机制。
今天小编就为大家分享一篇关于mysql+spring+mybatis实现数据库读写分离的代码配置,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
springboot+druid+mybatis多数据源动态切换,基于sql类型完成读写分离操作
本文主要介绍了Spring+MyBatis实现数据库读写分离方案。具有一定的参考价值,下面跟着小编一起来看下吧
主要给大家介绍了关于spring boot + mybatis如何实现数据库的读写分离的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用spring boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
本篇文章主要介绍了Spring+MyBatis实现数据读写分离的实例代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
主要介绍了Spring+Mybatis 实现aop数据库读写分离与多数据库源配置操作,需要的朋友可以参考下
shawn-rwdbspring+mybatis实现数据库读写分离如果你的后台结构是spring+mybatis,可以通过spring的AbstractRoutingDataSource和mybatis Plugin拦截器实现非常友好的读写分离,原有代码不需要任何改变。
提高访问性能和系统可扩展性。通过将读取操作分配给专门负责读取的从库,可以将读取操作的负载分散到多个数据库实例,从而提升读取性能和系统的可扩展性