支持多数据源

dep_wangsr
RuoYi 6 years ago committed by Limy
parent ad322f6948
commit 5a0ab9bfac

@ -115,7 +115,7 @@
<!--阿里数据库连接池 --> <!--阿里数据库连接池 -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid</artifactId> <artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version> <version>${druid.version}</version>
</dependency> </dependency>

@ -3,15 +3,14 @@ package com.ruoyi;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/** /**
* *
* *
* @author ruoyi * @author ruoyi
*/ */
@SpringBootApplication @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@EnableTransactionManagement
@MapperScan("com.ruoyi.project.*.*.mapper") @MapperScan("com.ruoyi.project.*.*.mapper")
public class RuoYiApplication public class RuoYiApplication
{ {

@ -0,0 +1,60 @@
package com.ruoyi.framework.aspectj;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Ds;
import com.ruoyi.framework.datasource.DataSourceContextHolder;
/**
*
*
* @author ruoyi
*/
@Aspect
@Order(1)
@Component
public class DsAspect
{
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(com.ruoyi.framework.aspectj.lang.annotation.Ds)")
public void dataSourcePointCut()
{
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable
{
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
if (method.isAnnotationPresent(Ds.class))
{
Ds dataSource = method.getAnnotation(Ds.class);
if (StringUtils.isNotNull(dataSource) && StringUtils.isNotEmpty(dataSource.name()))
{
DataSourceContextHolder.setDB(dataSource.name());
}
}
try
{
return point.proceed();
}
finally
{
DataSourceContextHolder.clearDB();
}
}
}

@ -0,0 +1,23 @@
package com.ruoyi.framework.aspectj.lang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.framework.aspectj.lang.constant.DataSourceName;
/**
*
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ds
{
/**
*
*/
String name() default DataSourceName.MASTER;
}

@ -0,0 +1,16 @@
package com.ruoyi.framework.aspectj.lang.constant;
/**
*
*
* @author ruoyi
*
*/
public class DataSourceName
{
/** 主库 */
public static final String MASTER = "master";
/** 从库 */
public static final String SLAVE = "slave";
}

@ -1,161 +1,47 @@
package com.ruoyi.framework.config; package com.ruoyi.framework.config;
import java.sql.SQLException; import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.slf4j.Logger; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet; import com.ruoyi.framework.aspectj.lang.constant.DataSourceName;
import com.alibaba.druid.support.http.WebStatFilter; import com.ruoyi.framework.datasource.DynamicDataSource;
/** /**
* Druid * druid
* *
* @author ruoyi * @author ruoyi
*/ */
@Configuration @Configuration
public class DruidConfig public class DruidConfig
{ {
private static final Logger log = LoggerFactory.getLogger(DruidConfig.class); @Bean
@ConfigurationProperties("spring.datasource.druid.master")
@Value("${spring.datasource.url}") public DataSource masterDataSource()
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("{spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean(initMethod = "init", destroyMethod = "close") /** 声明其为Bean实例 */
@Primary /** 在同样的DataSource中首先使用被标注的DataSource */
public DataSource dataSource()
{
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
/** configuration */
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try
{
datasource.setFilters(filters);
}
catch (SQLException e)
{ {
log.error("druid configuration initialization filter", e); return DruidDataSourceBuilder.create().build();
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
} }
/**
* StatViewServlet web.xmlservlet
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean @Bean
public ServletRegistrationBean druidServlet() @ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "open", havingValue = "true")
public DataSource slaveDataSource()
{ {
ServletRegistrationBean reg = new ServletRegistrationBean(); return DruidDataSourceBuilder.create().build();
reg.setServlet(new StatViewServlet());
reg.addUrlMappings("/monitor/druid/*");
/** 白名单 */
// reg.addInitParameter("allow", "10.211.61.45,127.0.0.1,123.207.20.136");
/** IP黑名单(共同存在时deny优先于allow) */
// reg.addInitParameter("deny", "10.211.61.4");
/** 是否能够重置数据 禁用HTML页面上的“Reset All”功能 */
reg.addInitParameter("resetEnable", "false");
return reg;
} }
/** @Bean(name = "dynamicDataSource")
* filterRegistrationBean web.xmlFilter @Primary
*/ public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource)
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean filterRegistrationBean()
{ {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); Map<Object, Object> targetDataSources = new HashMap<>();
filterRegistrationBean.setFilter(new WebStatFilter()); targetDataSources.put(DataSourceName.MASTER, masterDataSource);
/** 添加过滤规则. */ targetDataSources.put(DataSourceName.SLAVE, slaveDataSource);
filterRegistrationBean.addUrlPatterns("/*"); return new DynamicDataSource(masterDataSource, targetDataSources);
/** 监控选项滤器 */
filterRegistrationBean.addInitParameter("DruidWebStatFilter", "/*");
/** 添加不需要忽略的格式信息. */
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/monitor/druid/*");
/** 配置profileEnable能够监控单个url调用的sql列表 */
filterRegistrationBean.addInitParameter("profileEnable", "true");
/** 当前的cookie的用户 */
filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
/** 当前的session的用户 */
filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
return filterRegistrationBean;
} }
} }

@ -0,0 +1,35 @@
package com.ruoyi.framework.datasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 线
*
* @author ruoyi
*/
public class DataSourceContextHolder
{
public static final Logger log = LoggerFactory.getLogger(DataSourceContextHolder.class);
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 设置数据源名
public static void setDB(String dbType)
{
log.info("切换到{}数据源", dbType);
contextHolder.set(dbType);
}
// 获取数据源名
public static String getDB()
{
return contextHolder.get();
}
public static void clearDB()
{
contextHolder.remove();
}
}

@ -0,0 +1,27 @@
package com.ruoyi.framework.datasource;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
*
*
* @author ruoyi
*/
public class DynamicDataSource extends AbstractRoutingDataSource
{
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
{
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey()
{
return DataSourceContextHolder.getDB();
}
}

@ -87,15 +87,5 @@ public class PasswordService
{ {
//System.out.println(new PasswordService().encryptPassword("admin", "admin123", "111111")); //System.out.println(new PasswordService().encryptPassword("admin", "admin123", "111111"));
//System.out.println(new PasswordService().encryptPassword("ry", "admin123", "222222")); //System.out.println(new PasswordService().encryptPassword("ry", "admin123", "222222"));
System.out.println(new PasswordService().encryptPassword("ly", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("ce", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("zs", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("ls", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("ww", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("zl", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("sq", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("zb", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("wj", "admin123", "123456"));
System.out.println(new PasswordService().encryptPassword("ys", "admin123", "123456"));
} }
} }

@ -1,32 +1,45 @@
#dubbo配置 #数据源配置
spring: spring:
datasource: datasource:
type: com.alibaba.druid.pool.DruidDataSource type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver driverClassName: com.mysql.jdbc.Driver
#url: jdbc:mysql://10.213.24.45:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true druid:
master: #主库
url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true
username: root username: root
password: password password: password
# 初始化大小,最小,最大 #slave: #从库
initialSize: 1 # open: true
minIdle: 3 # url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true
maxActive: 20 # username: root
# password: password
# 初始连接数
initial-size: 10
# 最大连接池数量
max-active: 100
# 最小连接池数量
min-idle: 10
# 配置获取连接等待超时的时间 # 配置获取连接等待超时的时间
maxWait: 60000 max-wait: 60000
# 打开PSCache并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000 timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒 # 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000 min-evictable-idle-time-millis: 300000
validationQuery: select 'x' validation-query: SELECT 1 FROM DUAL
testWhileIdle: true test-while-idle: true
testOnBorrow: false test-on-borrow: false
testOnReturn: false test-on-return: false
# 打开PSCache并且指定每个连接上PSCache的大小 stat-view-servlet:
poolPreparedStatements: true enabled: true
maxPoolPreparedStatementPerConnectionSize: 20 url-pattern: /monitor/druid/*
# 配置监控统计拦截的filters去掉后监控界面sql无法统计'wall'用于防火墙 filter:
filters: stat,wall,slf4j stat:
# 通过connectProperties属性来打开mergeSql功能慢SQL记录 log-slow-sql: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 slow-sql-millis: 1000
# 合并多个DruidDataSource的监控数据 merge-sql: false
#useGlobalDataSourceStat: true wall:
config:
multi-statement-allow: true

@ -1,40 +0,0 @@
package com.ruoyi.common.utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* AddressUtils Tester.
*
* @author Leonhardt
* @version 1.0
* @since 07/22/2018
*/
public class AddressUtilsTest
{
@Before
public void before() throws Exception
{
}
@After
public void after() throws Exception
{
}
/**
* Method: getRealAddressByIP(String ip)
* <p>
*/
@Test
public void testGetRealAddressByIP() throws Exception
{
// TODO: Test goes here...
String ipAddress = AddressUtils.getRealAddressByIP("121.8.250.1");
System.out.println(ipAddress);
}
}

@ -1,124 +0,0 @@
package com.ruoyi.project.system.dept.service;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.Map;
/**
* DeptServiceImpl Tester.
*
* @author Leonhardt
* @version 1.0
* @since 07/22/2018
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class DeptServiceImplTest
{
@Autowired
private IDeptService deptService;
@Before
public void before() throws Exception
{
}
@After
public void after() throws Exception
{
}
/**
* Method: selectDeptList(Dept dept)
*/
@Test
public void testSelectDeptList() throws Exception
{
// TODO: Test goes here...
}
/**
* Method: selectDeptAll()
*/
@Test
public void testSelectDeptAll() throws Exception
{
// TODO: Test goes here...
Assert.assertEquals(deptService.selectDeptAll().size(), 10);
}
/**
* Method: selectDeptTree()
*/
@Test
public void testSelectDeptTree() throws Exception
{
// TODO: Test goes here...
List<Map<String, Object>> trees = deptService.selectDeptTree();
trees.stream().forEach(tree -> System.out.println(tree));
}
/**
* Method: selectDeptCount(Long parentId)
*/
@Test
public void testSelectDeptCount() throws Exception
{
// TODO: Test goes here...
Assert.assertEquals(10, deptService.selectDeptCount(0L));
}
/**
* Method: checkDeptExistUser(Long deptId)
*/
@Test
public void testCheckDeptExistUser() throws Exception
{
// TODO: Test goes here...
}
/**
* Method: deleteDeptById(Long deptId)
*/
@Test
public void testDeleteDeptById() throws Exception
{
// TODO: Test goes here...
}
/**
* Method: saveDept(Dept dept)
*/
@Test
public void testSaveDept() throws Exception
{
// TODO: Test goes here...
}
/**
* Method: selectDeptById(Long deptId)
*/
@Test
public void testSelectDeptById() throws Exception
{
// TODO: Test goes here...
Assert.assertNotNull("若依集团不存在", deptService.selectDeptById(100L));
}
/**
* Method: checkDeptNameUnique(Dept dept)
*/
@Test
public void testCheckDeptNameUnique() throws Exception
{
// TODO: Test goes here...
}
}
Loading…
Cancel
Save