文章目录
- 1. 引入Maven依赖
- 2.引入配置文件
- 3.兼容之前的数据库源,使用现在的sharding数据库源(shardingjdbc默认的数据源),但是配置好文件之后是没有生效的,需要加配置文件覆盖
- 4. 检测是否成功
- 5. 如何使用,在需要使用的类或者方法上面加上如下注解 @DataSource(DataSourceType.SHARDING)
1. 引入Maven依赖
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>sharding-jdbc-spring-boot-starter</artifactId><version>4.1.1</version></dependency>
注意: 是否和你的springboot是兼容的。
2.引入配置文件
# 项目相关配置
ruoyi:# 名称name: RuoYi# 版本version: 3.8.7# 版权年份copyrightYear: 2023# 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)profile: D:/ruoyi/uploadPath# 获取ip地址开关addressEnabled: false# 验证码类型 math 数字计算 char 字符验证captchaType: math
# 开发环境配置
server:# 服务器的HTTP端口,默认为8080port: 28001servlet:# 应用的访问路径context-path: /tomcat:# tomcat的URI编码uri-encoding: UTF-8# 连接数满后的排队数,默认为100accept-count: 1000threads:# tomcat最大线程数,默认为200max: 800# Tomcat启动初始化的线程数,默认值10min-spare: 100# 日志配置
logging:level:com.ruoyi: debugorg.springframework: warnio.swagger.models.parameters.AbstractSerializableParameter: error
# config: ./conf/logback-spring-admin.xmllog:level: infopath: ./logs#logging:
# level:
# io.swagger.models.parameters.AbstractSerializableParameter: error
# config: conf/logback-spring-admin.xml
#log:
# level: info
# path: ./logs# 用户配置
user:password:# 密码最大错误次数maxRetryCount: 10# 密码锁定时间(默认10分钟)lockTime: 5# Spring配置
spring:main:allow-bean-definition-overriding: truedatasource:type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: com.mysql.cj.jdbc.Driverdruid:# 主库数据源
# master:
# url: jdbc:mysql://localhost:3306/antcash?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
# username: root
# password: xxxxxx# 实际开发库master:url: jdbc:mysql://xxxxxxx:3306/antcash_dev_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8username: antcash_devpassword: xxxxxx# localhost
# url: jdbc:mysql://localhost:3306/antcash?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
# username: root
# password: roothouzhicong# Brazil
# url: jdbc:mysql://52.3.3.7:3306/runscore?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
# username: runscore
# password: gz_rs2023!# 从库数据源slave:# 从数据源开关/默认关闭enabled: falseurl:username:password:# 初始连接数initialSize: 5# 最小连接池数量minIdle: 10# 最大连接池数量maxActive: 20# 配置获取连接等待超时的时间maxWait: 60000# 配置连接超时时间connectTimeout: 30000# 配置网络超时时间socketTimeout: 60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒timeBetweenEvictionRunsMillis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒minEvictableIdleTimeMillis: 300000# 配置一个连接在池中最大生存的时间,单位是毫秒maxEvictableIdleTimeMillis: 900000# 配置检测连接是否有效validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsewebStatFilter:enabled: truestatViewServlet:enabled: true# 设置白名单,不填则允许所有访问allow:url-pattern: /druid/*# 控制台管理用户名和密码login-username: ruoyilogin-password: 123456filter:stat:enabled: true# 慢SQL记录log-slow-sql: trueslow-sql-millis: 2000merge-sql: truewall:config:multi-statement-allow: trueshardingsphere:props:max:connections:size:per:query: 5datasource:names: shardingsharding:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://xxxxxxx:3306/antcash_dev_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=trueusername: xxxpassword: xxxx
# url: jdbc:mysql://xxxxxxx:3306/runscore?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
# username: runscore
# password: xxxxxx!sharding:tables:merchant_order:actual-data-nodes: sharding.merchant_order_$->{1..50}table-strategy:standard:sharding-column: idprecise-algorithm-class-name: com.ruoyi.common.config.TableShardingAlgorithmmerchant_order_pay_info:actual-data-nodes: sharding.merchant_order_pay_info_$->{1..50}table-strategy:standard:sharding-column: idprecise-algorithm-class-name: com.ruoyi.common.config.TableShardingAlgorithmaccount_change_log:actual-data-nodes: sharding.account_change_log_$->{1..50}table-strategy:standard:sharding-column: idprecise-algorithm-class-name: com.ruoyi.common.config.TableShardingAlgorithm
# props:
# sql-show: true
# executor-size: 16# 资源信息messages:# 国际化资源文件路径basename: i18n/messages
# profiles:
# active: druid# 文件上传servlet:multipart:# 单个文件大小max-file-size: 10MB# 设置总上传的文件大小max-request-size: 20MB# 服务模块devtools:restart:# 热部署开关enabled: true# redis 配置redis:# 地址host: xxxxxx
# host: localhost# 端口,默认为6379port: 6378# 数据库索引database: 0# 密码password:# 连接超时时间timeout: 10slettuce:pool:# 连接池中的最小空闲连接min-idle: 0# 连接池中的最大空闲连接max-idle: 8# 连接池的最大数据库连接数max-active: 8# #连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1ms# token配置
token:# 令牌自定义标识header: Authorization# 令牌密钥secret: abcdefghijklmnopqrstuvwxyz# 令牌有效期(默认30分钟)expireTime: 300# MyBatis配置
#mybatis:
# # 搜索指定包别名
# typeAliasesPackage: com.ruoyi.**.domain
# # 配置mapper的扫描,找到所有的mapper.xml映射文件
# mapperLocations: classpath*:mapper/**/*.xml
# # 加载全局的配置文件
# configLocation: classpath:mybatis/mybatis-config.xml
mybatis-plus:# 搜索指定包别名typeAliasesPackage: com.ruoyi.**.domain# 配置mapper的扫描,找到所有的mapper.xml映射文件mapperLocations: classpath*:mapper/**/*Mapper.xml# 加载全局的配置文件configLocation: classpath:mybatis/mybatis-config.xml# PageHelper分页插件
pagehelper:helperDialect: mysqlsupportMethodsArguments: trueparams: count=countSql# Swagger配置
swagger:# 是否开启swaggerenabled: false# 请求前缀pathMapping: /dev-api# 防止XSS攻击
xss:# 过滤开关enabled: true# 排除链接(多个用逗号分隔)excludes: /system/notice# 匹配链接urlPatterns: /system/*,/monitor/*,/tool/*configuration:map-underscore-to-camel-case: true
3.兼容之前的数据库源,使用现在的sharding数据库源(shardingjdbc默认的数据源),但是配置好文件之后是没有生效的,需要加配置文件覆盖
在注解DataSourceType里面加上sharding
/*** 数据源** @author ruoyi*/
public enum DataSourceType
{/*** 主库*/MASTER,/*** 从库*/SLAVE,SHARDING,
}
DruidConfig加上shardingjdbcsource数据源:
package com.ruoyi.framework.config;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.properties.DruidProperties;
import com.ruoyi.framework.datasource.DynamicDataSource;import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;/*** druid 配置多数据源** @author ruoyi*/
@Configuration
public class DruidConfig
{@Bean@ConfigurationProperties("spring.datasource.druid.master")public DataSource masterDataSource(DruidProperties druidProperties){DruidDataSource dataSource = DruidDataSourceBuilder.create().build();return druidProperties.dataSource(dataSource);}@Bean@ConfigurationProperties("spring.datasource.druid.slave")@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")public DataSource slaveDataSource(DruidProperties druidProperties){DruidDataSource dataSource = DruidDataSourceBuilder.create().build();return druidProperties.dataSource(dataSource);}@Bean(name = "dynamicDataSource")@Primarypublic DynamicDataSource dataSource(DataSource masterDataSource){Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");setDataSource(targetDataSources, DataSourceType.SHARDING.name(), "shardingDataSource");return new DynamicDataSource(masterDataSource, targetDataSources);}/*** 设置数据源** @param targetDataSources 备选数据源集合* @param sourceName 数据源名称* @param beanName bean名称*/public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName){try{DataSource dataSource = SpringUtils.getBean(beanName);targetDataSources.put(sourceName, dataSource);}catch (Exception e){log.error(e.getMessage());}}/** 解决druid 日志报错:discard long time none received connection:xxx */@PostConstructpublic void setProperties() {System.setProperty("druid.mysql.usePingMethod", "false");}/*** 去除监控页面底部的广告*/@SuppressWarnings({ "rawtypes", "unchecked" })@Bean@ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties){// 获取web监控页面的参数DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();// 提取common.js的配置路径String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");final String filePath = "support/http/resources/js/common.js";// 创建filter进行过滤Filter filter = new Filter(){@Overridepublic void init(javax.servlet.FilterConfig filterConfig) throws ServletException{}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException{chain.doFilter(request, response);// 重置缓冲区,响应头不会被重置response.resetBuffer();// 获取common.jsString text = Utils.readFromResource(filePath);// 正则替换banner, 除去底部的广告信息text = text.replaceAll("<a.*?banner\"></a><br/>", "");text = text.replaceAll("powered.*?shrek.wang</a>", "");response.getWriter().write(text);}@Overridepublic void destroy(){}};FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setFilter(filter);registrationBean.addUrlPatterns(commonJsPattern);return registrationBean;}
}
加上shardingjdbc自己的数据源配置:
package com.ruoyi.framework.config;import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.StandardShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;/** @Classname ShardingDataSourceConfig @Description @Date 2023-5-23 15:38 @Author 无朽 */
@Configuration
public class ShardingDataSourceConfig {@Bean(name = "shardingDataSource")public DataSource shardingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource)throws SQLException {Map<String, DataSource> dataSourceMap = new HashMap<>(1);dataSourceMap.put("masterDataSource", masterDataSource);// 配置分片规则/* ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfiguration);shardingRuleConfig.getTableRuleConfigs().add(fileTableRuleConfiguration);*/// 获取数据源对象DataSource dataSource =ShardingDataSourceFactory.createDataSource(dataSourceMap, null, getProperties());return dataSource;}/** 系统参数配置 */private Properties getProperties() {Properties shardingProperties = new Properties();shardingProperties.put("sql.show", true);return shardingProperties;}
}
4. 检测是否成功
有加载 如下 信息表示成功: