Commit 9d7598f8 by fengshuonan

完善多数据源的配置

parent 8b477068
......@@ -43,7 +43,7 @@
<dependency>
<groupId>cn.stylefeng.roses</groupId>
<artifactId>kernel-core</artifactId>
<version>1.2.0</version>
<version>1.2.1</version>
</dependency>
<!--数据库驱动,可根据自己需要自行删减-->
......
......@@ -15,11 +15,8 @@
*/
package cn.stylefeng.guns.config.datasource;
import cn.stylefeng.roses.core.datascope.DataScopeInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
......@@ -35,21 +32,5 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan(basePackages = {"cn.stylefeng.guns.modular.*.mapper"})
public class SingleDataSourceConfig {
/**
* 数据范围mybatis插件
*/
@Bean
public DataScopeInterceptor dataScopeInterceptor() {
return new DataScopeInterceptor();
}
/**
* 乐观锁mybatis插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
......@@ -99,6 +99,8 @@ public class MultiDataSourceConfig {
AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
atomikosDataSourceBean.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
atomikosDataSourceBean.setUniqueResourceName(dataSourceName);
atomikosDataSourceBean.setMaxPoolSize(20);
atomikosDataSourceBean.setBorrowConnectionTimeout(60);
atomikosDataSourceBean.setXaProperties(druidProperties.createProperties());
return atomikosDataSourceBean;
}
......
......@@ -16,26 +16,33 @@
package cn.stylefeng.guns.config.datasource.multi;
import cn.stylefeng.roses.core.config.properties.DruidProperties;
import cn.stylefeng.roses.core.datascope.DataScopeInterceptor;
import cn.stylefeng.roses.core.mutidatasource.mybatis.OptionalSqlSessionTemplate;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
......@@ -51,10 +58,32 @@ import java.util.Map;
@ConditionalOnProperty(prefix = "guns.muti-datasource", name = "open", havingValue = "true")
public class MultiSqlSessionFactoryConfig {
/**
* xml文件的位置,改包了注意修改哦
*/
public static final String MAPPING_XML_CLASSPATH = "classpath:cn/stylefeng/guns/modular/**/mapping/*.xml";
private final MybatisPlusProperties properties;
private final Interceptor[] interceptors;
private final ResourceLoader resourceLoader;
private final DatabaseIdProvider databaseIdProvider;
private final List<ConfigurationCustomizer> configurationCustomizers;
private final ApplicationContext applicationContext;
public MultiSqlSessionFactoryConfig(MybatisPlusProperties properties,
ObjectProvider<Interceptor[]> interceptorsProvider,
ResourceLoader resourceLoader,
ObjectProvider<DatabaseIdProvider> databaseIdProvider,
ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
ApplicationContext applicationContext) {
this.properties = properties;
this.interceptors = interceptorsProvider.getIfAvailable();
this.resourceLoader = resourceLoader;
this.databaseIdProvider = databaseIdProvider.getIfAvailable();
this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable();
this.applicationContext = applicationContext;
}
/**
* 主sqlSessionFactory
......@@ -96,44 +125,38 @@ public class MultiSqlSessionFactoryConfig {
}
/**
* mybatis-plus分页插件
* 创建数据源
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
private SqlSessionFactory createSqlSessionFactory(DataSource dataSource) {
try {
MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
/**
* 数据范围mybatis插件
*/
@Bean
public DataScopeInterceptor dataScopeInterceptor() {
return new DataScopeInterceptor();
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
/**
* 乐观锁mybatis插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
factory.setMapperLocations(this.properties.resolveMapperLocations());
}
GlobalConfig globalConfig = this.properties.getGlobalConfig();
if (this.applicationContext.getBeanNamesForType(MetaObjectHandler.class,
false, false).length > 0) {
MetaObjectHandler metaObjectHandler = this.applicationContext.getBean(MetaObjectHandler.class);
globalConfig.setMetaObjectHandler(metaObjectHandler);
}
/**
* 创建数据源
*/
private SqlSessionFactory createSqlSessionFactory(DataSource dataSource) {
try {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPING_XML_CLASSPATH));
bean.setVfs(SpringBootVFS.class);
bean.setPlugins(new Interceptor[]{
paginationInterceptor(),
dataScopeInterceptor(),
optimisticLockerInterceptor()
});
return bean.getObject();
//globalConfig中有缓存sqlSessionFactory,目前还没别的办法
SqlSessionFactory sqlSessionFactory = factory.getObject();
globalConfig.signGlobalConfig(sqlSessionFactory);
factory.setGlobalConfig(globalConfig);
return factory.getObject();
} catch (Exception e) {
log.error("初始化SqlSessionFactory错误!", e);
throw new ServiceException(500, "初始化SqlSessionFactory错误!");
......
......@@ -32,7 +32,7 @@
ELSE
'false'
END
) as open from sys_dept
) as 'open' from sys_dept
</select>
<select id="list" resultType="map">
......
......@@ -70,7 +70,7 @@
ELSE
'false'
END
) as open
) as 'open'
FROM
sys_menu m1
LEFT join sys_menu m2 ON m1.PCODE = m2.CODE
......@@ -98,7 +98,7 @@
ELSE
'false'
END
) as open,
) as 'open',
(
CASE
WHEN (m3.MENU_ID = 0 OR m3.MENU_ID
......
......@@ -38,7 +38,7 @@
<select id="roleTreeList" resultType="cn.stylefeng.guns.core.common.node.ZTreeNode">
select ROLE_ID AS id, PID as pId,
NAME as name, (case when (PID = 0 or PID is null) then 'true'
else 'false' end) as `open` from sys_role
else 'false' end) as 'open' from sys_role
</select>
<select id="roleTreeListByRoleId" resultType="cn.stylefeng.guns.core.common.node.ZTreeNode">
......@@ -53,7 +53,7 @@
ELSE
'false'
END
) as `open`,
) as 'open',
(
CASE
WHEN (r1.ROLE_ID = 0 OR r1.ROLE_ID IS NULL) THEN
......
package cn.stylefeng.guns.modular.system.service;
import cn.stylefeng.guns.modular.system.entity.User;
import cn.stylefeng.guns.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.modular.system.model.UserDto;
import cn.stylefeng.roses.core.mutidatasource.annotion.DataSource;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 管理员表 服务实现类
* </p>
*
* @author stylefeng
* @since 2018-12-07
*/
@Service
public class TestService extends ServiceImpl<UserMapper, User> {
@Autowired
private UserService userService;
@DataSource(name = "otherdb")
public void addddd() {
UserDto user = new UserDto();
user.setAccount("123123");
user.setPassword("1231231232");
userService.addUser(user);
}
}
......@@ -30,6 +30,7 @@ spring:
mybatis-plus:
typeAliasesPackage: cn.stylefeng.guns.modular.system.model
mapper-locations: classpath:cn/stylefeng/guns/modular/**/mapping/*.xml
log:
path: guns-logs
\ No newline at end of file
package cn.stylefeng.guns.multi.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author fengshuonan
* @since 2018-07-10
*/
public class Test implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "aaa", type = IdType.AUTO)
private Integer aaa;
private String bbb;
public Integer getAaa() {
return aaa;
}
public void setAaa(Integer aaa) {
this.aaa = aaa;
}
public String getBbb() {
return bbb;
}
public void setBbb(String bbb) {
this.bbb = bbb;
}
@Override
public String toString() {
return "Test{" +
"aaa=" + aaa +
", bbb=" + bbb +
"}";
}
}
package cn.stylefeng.guns.multi.mapper;
import cn.stylefeng.guns.multi.entity.Test;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author fengshuonan
* @since 2018-07-10
*/
public interface TestMapper extends BaseMapper<Test> {
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.stylefeng.guns.multi.mapper.TestMapper">
<!-- 开启二级缓存 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="cn.stylefeng.guns.multi.entity.Test">
<id column="aaa" property="aaa" />
<result column="bbb" property="bbb" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
aaa, bbb
</sql>
</mapper>
package cn.stylefeng.guns.multi.service;
/**
* <p>
* 服务类
* </p>
*
* @author fengshuonan
* @since 2018-07-10
*/
public interface TestService {
/**
* 测试多数据源的业务
*
* @author stylefeng
* @Date 2017/6/23 23:02
*/
void testBiz();
/**
* 测试多数据源的业务
*
* @author stylefeng
* @Date 2017/6/23 23:02
*/
void testGuns();
}
package cn.stylefeng.guns.multi.service.impl;
import cn.stylefeng.guns.core.common.constant.DatasourceEnum;
import cn.stylefeng.guns.multi.entity.Test;
import cn.stylefeng.guns.multi.mapper.TestMapper;
import cn.stylefeng.guns.multi.service.TestService;
import cn.stylefeng.roses.core.mutidatasource.annotion.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 服务实现类
* </p>
*
* @author fengshuonan
* @since 2018-07-10
*/
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
@DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
@Transactional
public void testBiz() {
Test test = new Test();
test.setBbb("bizTest");
testMapper.insert(test);
}
@Override
@DataSource(name = DatasourceEnum.DATA_SOURCE_GUNS)
@Transactional
public void testGuns() {
Test test = new Test();
test.setBbb("gunsTest");
testMapper.insert(test);
}
}
package cn.stylefeng.guns.multi.test;
import cn.stylefeng.guns.base.BaseJunit;
import cn.stylefeng.guns.multi.service.TestService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 业务测试
*
* @author fengshuonan
* @date 2017-06-23 23:12
*/
public class BizTest extends BaseJunit {
@Autowired
private TestService testService;
@Test
public void test() {
testService.testGuns();
testService.testBiz();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment