feat:多数据源模块

master
hbr 2024-06-04 18:36:20 +08:00
parent 58333c29eb
commit d89b7ab7ce
30 changed files with 997 additions and 22 deletions

View File

@ -219,6 +219,8 @@
<module>zhiLian-iotdb</module>
<module>zhiLian-vehicle</module>
<module>zhiLian-business/zhiLian-data-service</module>
<module>zhiLian-cloud-datasource</module>
<module>zhiLian-cloud-datasource/zhiLian-datasource-service</module>
</modules>
<packaging>pom</packaging>

View File

@ -96,7 +96,7 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
int i = businessMapper.insertBusiness(business);
System.out.println(business);
SysUser sysUser = SysUser.builder()
.userName(business.getName() + business.getId())
.userName(business.getName())
.password("admin123")
.nickName(business.getName())
.email(business.getBusinessEmail())
@ -107,6 +107,26 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
Result add = remoteUserService.add(sysUser);
return i;
}
/**
*
*
* @param business
* @return
*/
@Override
public int updateBusiness(Business business)
{
business.setUpdateTime(DateUtils.getNowDate());
httpConnectMysql(business);
return businessMapper.updateBusiness(business);
}
/**
* redis
* @param business
*/
public void httpConnectMysql(Business business){
if (business.getBusinessStates().equals(2) ) {
if (!redisTemplate.hasKey(business.getId()+business.getName())){
@ -117,6 +137,10 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
}
/**
* http URL
* @param business
*/
private static void extracted(Business business) {
String postUrl="http://122.51.111.225:10006/webhook/%E6%96%B0%E5%BB%BA%E4%BC%81%E4%B8%9A%E6%95%B0%E6%8D%AE%E6%BA%90";
HashMap<String, String> hashMap = new HashMap<>();
@ -134,8 +158,8 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
httpConn.setRequestProperty("Content-Type", "application/json");
// 打开输出流,默认是false
httpConn.setDoOutput(true);
// 打开输入流,默认是true,可省略
httpConn.setDoInput(true);
// // 打开输入流,默认是true,可省略
// httpConn.setDoInput(true);
// 4.从HttpURLConnection获取输出流和写数据
OutputStream oStream = httpConn.getOutputStream();
oStream.write(json.getBytes());
@ -156,20 +180,6 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
}
}
/**
*
*
* @param business
* @return
*/
@Override
public int updateBusiness(Business business)
{
business.setUpdateTime(DateUtils.getNowDate());
httpConnectMysql(business);
return businessMapper.updateBusiness(business);
}
/**
*
*

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zhiLian</groupId>
<artifactId>zhiLian-server</artifactId>
<version>3.6.3</version>
</parent>
<artifactId>zhiLian-cloud-datasource</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zhiLian</groupId>
<artifactId>zhiLian-server</artifactId>
<version>3.6.3</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>zhiLian-datasource-service</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<description>
zhiLian-datasource-service多数据源配置
</description>
<dependencies>
<!-- SpringCloud Alibaba Nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- SpringCloud Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- SpringBoot Actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.fox.version}</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- ZhiLian Common DataSource -->
<dependency>
<groupId>com.zhiLian</groupId>
<artifactId>zhiLian-common-datasource</artifactId>
</dependency>
<!-- ZhiLian Common DataScope -->
<dependency>
<groupId>com.zhiLian</groupId>
<artifactId>zhiLian-common-datascope</artifactId>
</dependency>
<!-- ZhiLian Common Log -->
<dependency>
<groupId>com.zhiLian</groupId>
<artifactId>zhiLian-common-log</artifactId>
</dependency>
<!-- ZhiLian Common Swagger -->
<dependency>
<groupId>com.zhiLian</groupId>
<artifactId>zhiLian-common-swagger</artifactId>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 加入maven deploy插件当在deploy时忽略些model-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,39 @@
package com.zhiLian.datasource;
import com.zhiLian.common.core.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import static com.zhiLian.datasource.contents.DatasourceContent.*;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:15
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DataSourceInfo {
private String key;
private String url;
private String userName;
private String password;
public static DataSourceInfo databaseNameBuild(String databaseName){
return DataSourceInfo.builder()
.key(databaseName)
.url(StringUtils.format(DATASOURCE_URL, databaseName))
.password(PASSWORD)
.userName(USER_NAME)
.build();
}
}

View File

@ -0,0 +1,42 @@
package com.zhiLian.datasource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
/**
*
*
* @author Dongzl
*/
@Slf4j
public class DynamicDataSourceHolder {
/**
*
*/
private static final ThreadLocal<String> DYNAMIC_DATASOURCE_KEY = new ThreadLocal<>();
/**
* /线使
*/
public static void setDynamicDataSourceKey(String key){
log.info("数据源切换为:{}",key);
DYNAMIC_DATASOURCE_KEY.set(key);
}
/**
* 使mater
*/
public static String getDynamicDataSourceKey(){
String key = DYNAMIC_DATASOURCE_KEY.get();
Assert.notNull(key, "请携带数据标识");
return key;
}
/**
*
*/
public static void removeDynamicDataSourceKey(){
log.info("移除数据源:{}",DYNAMIC_DATASOURCE_KEY.get());
DYNAMIC_DATASOURCE_KEY.remove();
}
}

View File

@ -0,0 +1,27 @@
package com.zhiLian.datasource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.zhiLian.common.security.annotation.EnableCustomConfig;
import com.zhiLian.common.security.annotation.EnableMyFeignClients;
import com.zhiLian.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* BingRui.Hou
*
* @Description
* @ClassName ZhiLianDataSourceApplication
* @Date 2024/06/03 14:06
*/
@EnableCustomConfig
@EnableCustomSwagger2
@EnableMyFeignClients
@SpringBootApplication(exclude = {DynamicDataSourceAutoConfiguration.class,DataSourceAutoConfiguration.class })
public class ZhiLianDataSourceApplication {
public static void main(String[] args) {
SpringApplication.run(ZhiLianDataSourceApplication.class, args);
}
}

View File

@ -0,0 +1,44 @@
package com.zhiLian.datasource.config;
import com.zhiLian.common.security.utils.SecurityUtils;
import com.zhiLian.datasource.DynamicDataSourceHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @author DongZl
* @description:
* @Date 2023-8-2 08:26
*/
@Aspect
@Component
public class DataSourceAsp {
@Pointcut("execution(public * com.zhiLian.datasource..*Controller.*(..))")
public void pointcut () {
}
/**
*
*/
@Before("pointcut()")
public void beforeMethod() {
Long storeId = SecurityUtils.getLoginUser().getUserid();
DynamicDataSourceHolder.setDynamicDataSourceKey("test_"+storeId);
}
/**
*
*
*
*/
@After("pointcut()")
public void afterMethod() {
DynamicDataSourceHolder.removeDynamicDataSourceKey();
}
}

View File

@ -0,0 +1,71 @@
package com.zhiLian.datasource.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.zhiLian.datasource.DataSourceInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:05
*/
@Log4j2
@Configuration
public class DruidConfig {
private List<DataSourceInfo> getDataSourceInfoList(){
List<String> databaseNameList = new ArrayList<>(){{
add("3306");
// add("3307");
}};
return databaseNameList.stream().map(DataSourceInfo::databaseNameBuild).toList();
}
/**
* @Description:
* @Author Dongzl
*/
public DruidDataSource createDataSourceConnection(DataSourceInfo dataSourceInfo) {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(dataSourceInfo.getUrl());
druidDataSource.setUsername(dataSourceInfo.getUserName());
druidDataSource.setPassword(dataSourceInfo.getPassword());
druidDataSource.setBreakAfterAcquireFailure(true);
druidDataSource.setConnectionErrorRetryAttempts(0);
try {
druidDataSource.getConnection(2000);
log.info("{} -> 数据源连接成功", dataSourceInfo.getKey());
return druidDataSource;
} catch (SQLException throwables) {
log.error("数据源 {} 连接失败,用户名:{},密码 {}",dataSourceInfo.getUrl(),dataSourceInfo.getUserName(),dataSourceInfo.getPassword());
return null;
}
}
@Bean
@Primary
public DynamicDataSource dynamicDataSource() {
Map<Object, Object> dataSourceMap = new HashMap<>();
getDataSourceInfoList().forEach(dataSourceInfo -> {
dataSourceMap.put(dataSourceInfo.getKey(), createDataSourceConnection(dataSourceInfo));
});
//设置动态数据源
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
dynamicDataSource.setTargetDataSources(dataSourceMap);
//将数据源信息备份在defineTargetDataSources中
dynamicDataSource.setDefineTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
}

View File

@ -0,0 +1,31 @@
package com.zhiLian.datasource.config;
import com.zhiLian.datasource.DynamicDataSourceHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import java.util.Map;
/**
*
* AddDefineDataSourceaddDefineDynamicDataSourcetargetdatasourcesmapmaptargetdatasourcesmap
* 使@DataSource(value = "数据源名称")DynamicDataSourceContextHolder.setContextKey("数据源名称")
* @author Dongzl
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DynamicDataSource extends AbstractRoutingDataSource {
//备份所有数据源信息,
private Map<Object, Object> defineTargetDataSources;
/**
* 线使
*/
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDynamicDataSourceKey();
}
}

View File

@ -0,0 +1,18 @@
package com.zhiLian.datasource.contents;
/**
* @Description:
* @Author Dongzl
* @Date 2022/8/18 16:33
*
*/
public class CommonConstant {
/**
*
*/
public static final String MASTER = "master";
/**
*
*/
public static final String SLAVE = "slave";
}

View File

@ -0,0 +1,15 @@
package com.zhiLian.datasource.contents;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:02
*/
public class DatasourceContent {
public final static String DATASOURCE_URL = "jdbc:mysql://122.51.111.225:{}/zhiLian-cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
public final static String USER_NAME = "root";
public final static String PASSWORD = "root";
}

View File

@ -0,0 +1,44 @@
package com.zhiLian.datasource.util;
import com.alibaba.druid.pool.DruidDataSource;
import com.zhiLian.datasource.DataSourceInfo;
import com.zhiLian.datasource.config.DruidConfig;
import com.zhiLian.datasource.config.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
/**
* @Description:
* @Author Dongzl
* @Date 2022/8/18 17:20
*
*/
@Slf4j
@Component
public class DataSourceService {
@Autowired
private DruidConfig druidConfig;
@Resource
private DynamicDataSource dynamicDataSource;
public void addDataSource(DataSourceInfo dataSourceInfo){
addDefineDynamicDataSource(druidConfig.createDataSourceConnection(dataSourceInfo), dataSourceInfo.getKey());
}
/**
* @Description: map
* @Author Dongzl
*/
public void addDefineDynamicDataSource(DruidDataSource druidDataSource, String dataSourceName){
Map<Object, Object> defineTargetDataSources = dynamicDataSource.getDefineTargetDataSources();
defineTargetDataSources.put(dataSourceName, druidDataSource);
dynamicDataSource.setTargetDataSources(defineTargetDataSources);
dynamicDataSource.afterPropertiesSet();
}
}

View File

@ -0,0 +1,2 @@
Spring Boot Version: ${spring-boot.version}
Spring Application Name: ${spring.application.name}

View File

@ -0,0 +1,32 @@
# Tomcat
server:
port: 9206
# Spring
spring:
application:
# 应用名称
name: zhiLian-datasource
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 111.229.102.61:8848
# 命名空间
namespace: zhiLian
config:
# 配置中心地址
server-addr: 111.229.102.61:8848
# 命名空间
namespace: zhiLian
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
#logging:
# level:
# com.zhiLian.system.mapper: DEBUG

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 日志存放路径 -->
<property name="log.path" value="logs/zhiLian-datasource"/>
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.zhiLian" level="info"/>
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn"/>
<root level="info">
<appender-ref ref="console"/>
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info"/>
<appender-ref ref="file_error"/>
</root>
</configuration>

View File

@ -1,11 +1,13 @@
package com.zhiLian.vehicle;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.zhiLian.common.security.annotation.EnableCustomConfig;
import com.zhiLian.common.security.annotation.EnableMyFeignClients;
import com.zhiLian.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* BingRui.Hou
@ -17,7 +19,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableCustomConfig
@EnableCustomSwagger2
@EnableMyFeignClients
@SpringBootApplication
@SpringBootApplication(exclude = {DynamicDataSourceAutoConfiguration.class, DataSourceAutoConfiguration.class })
public class ZhiLianVehicleApplication {
public static void main (String[] args) {
SpringApplication.run(ZhiLianVehicleApplication.class, args);

View File

@ -26,9 +26,9 @@ import org.springframework.web.bind.annotation.RestController;
/**
* Controller
* Controller BingRui.Hou
*
* @author muyu
* @author
* @date 2024-05-31
*/
@RestController

View File

@ -25,7 +25,7 @@ import org.springframework.web.bind.annotation.RestController;
/**
* Controller
*
* @author muyu
* @author BingRui.Hou
* @date 2024-06-02
*/
@RestController

View File

@ -19,7 +19,7 @@ import java.util.List;
/**
* Controller
*
* @author muyu
* @author BingRui.Hou
* @date 2024-05-27
*/
@RestController

View File

@ -0,0 +1,63 @@
package com.zhiLian.vehicle.datasource;
import com.alibaba.druid.pool.DruidDataSource;
import com.zhiLian.vehicle.datasource.config.factory.DruidDataSourceFactory;
import com.zhiLian.vehicle.datasource.domain.DataSourceInfo;
import com.zhiLian.vehicle.datasource.domain.EntInfo;
import com.zhiLian.vehicle.datasource.config.role.DynamicDataSource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:05
*/
@Log4j2
@Configuration
public class ManyDataSource {
private List<EntInfo> dataSourceInfoList(){
List<EntInfo> databaseNameList = new ArrayList<>(){{
add(EntInfo.builder()
.entCode("test_1")
.ip("122.51.111.225")
.port(6666)
.build());
}};
return databaseNameList;
}
@Bean
@Primary
public DynamicDataSource dynamicDataSource(DruidDataSourceFactory druidDataSourceFactory) {
//查企业
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceInfoList()
.stream()
.map(entInfo->DataSourceInfo.hostAndPortBuild(entInfo.getEntCode(),entInfo.getIp(),entInfo.getPort()))
.forEach(dataSourceInfo -> {
dataSourceMap.put(dataSourceInfo.getKey(), druidDataSourceFactory.create(dataSourceInfo));
});
//设置动态数据源
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
dynamicDataSource.setTargetDataSources(dataSourceMap);
//将数据源信息备份在defineTargetDataSources中
dynamicDataSource.setDefineTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
}

View File

@ -0,0 +1,42 @@
package com.zhiLian.vehicle.datasource.config;
import com.zhiLian.common.security.utils.SecurityUtils;
import com.zhiLian.vehicle.datasource.config.holder.DynamicDataSourceHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* @author DongZl
* @description:
* @Date 2023-8-2 08:26
*/
@Aspect
@Component
public class DataSourceAsp {
@Pointcut("execution(public * com.zhiLian.vehicle.controller.*Controller.*(..))")
public void pointcut () {
}
/**
*
*/
@Before("pointcut()")
public void beforeMethod() {
Long storeId = SecurityUtils.getLoginUser().getUserid();
DynamicDataSourceHolder.setDynamicDataSourceKey("test_"+storeId);
}
/**
*
*
*
*/
@After("pointcut()")
public void afterMethod() {
DynamicDataSourceHolder.removeDynamicDataSourceKey();
}
}

View File

@ -0,0 +1,50 @@
package com.zhiLian.vehicle.datasource.config.factory;
import com.alibaba.druid.pool.DruidDataSource;
import com.zhiLian.vehicle.datasource.config.role.DynamicDataSource;
import com.zhiLian.vehicle.datasource.domain.DataSourceInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* BingRui.Hou
*
* @Description
* @ClassName DruidDataSourceFactory
* @Date 2024/06/04 14:47
*/
@Log4j2
@Component
public class DruidDataSourceFactory {
/**
* @Description:
* @Author Dongzl
*/
public DruidDataSource create(DataSourceInfo dataSourceInfo) {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(dataSourceInfo.getUrl());
druidDataSource.setUsername(dataSourceInfo.getUserName());
druidDataSource.setPassword(dataSourceInfo.getPassword());
druidDataSource.setBreakAfterAcquireFailure(true);
druidDataSource.setConnectionErrorRetryAttempts(0);
try {
druidDataSource.getConnection(2000);
log.info("{} -> 数据源连接成功", dataSourceInfo.getKey());
return druidDataSource;
} catch (SQLException throwables) {
log.error("数据源 {} 连接失败,用户名:{},密码 {}",dataSourceInfo.getUrl(),dataSourceInfo.getUserName(),dataSourceInfo.getPassword());
return null;
}
}
}

View File

@ -0,0 +1,43 @@
package com.zhiLian.vehicle.datasource.config.holder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
/**
*
*
* @author Dongzl
*/
@Slf4j
public class DynamicDataSourceHolder {
/**
*
*/
private static final ThreadLocal<String> DYNAMIC_DATASOURCE_KEY = new ThreadLocal<>();
/**
* /线使
*/
public static void setDynamicDataSourceKey(String key){
log.info("数据源切换为:{}",key);
DYNAMIC_DATASOURCE_KEY.set(key);
}
/**
* 使mater
*/
public static String getDynamicDataSourceKey(){
String key = DYNAMIC_DATASOURCE_KEY.get();
Assert.notNull(key, "请携带数据标识");
return key;
}
/**
*
*/
public static void removeDynamicDataSourceKey(){
log.info("移除数据源:{}",DYNAMIC_DATASOURCE_KEY.get());
DYNAMIC_DATASOURCE_KEY.remove();
}
}

View File

@ -0,0 +1,35 @@
package com.zhiLian.vehicle.datasource.config.role;
import com.zhiLian.vehicle.datasource.config.holder.DynamicDataSourceHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import java.util.Map;
/**
*
* AddDefineDataSourceaddDefineDynamicDataSourcetargetdatasourcesmapmaptargetdatasourcesmap
* 使@DataSource(value = "数据源名称")DynamicDataSourceContextHolder.setContextKey("数据源名称")
* @author Dongzl
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
*
*/
private Map<Object, Object> defineTargetDataSources;
/**
* 线使
*/
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDynamicDataSourceKey();
}
}

View File

@ -0,0 +1,15 @@
package com.zhiLian.vehicle.datasource.contents;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:02
*/
public class DatasourceContent {
public final static String DATASOURCE_URL = "jdbc:mysql://{}:{}/zhiLian-cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
public final static String USER_NAME = "root";
public final static String PASSWORD = "root";
}

View File

@ -0,0 +1,52 @@
package com.zhiLian.vehicle.datasource.domain;
import com.zhiLian.common.core.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import static com.zhiLian.vehicle.datasource.contents.DatasourceContent.*;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:15
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DataSourceInfo {
/**
*
*/
private String key;
/**
*
*/
private String url;
/**
*
*/
private String userName;
/**
*
*/
private String password;
public static DataSourceInfo hostAndPortBuild(String key,String host, Integer port){
return DataSourceInfo.builder()
.key(key)
.url(StringUtils.format(DATASOURCE_URL, host,port))
.password(PASSWORD)
.userName(USER_NAME)
.build();
}
}

View File

@ -0,0 +1,30 @@
package com.zhiLian.vehicle.datasource.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
/**
* BingRui.Hou
*
* @Description
* @ClassName EntInfo
* @Date 2024/06/04 14:34
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class EntInfo {
private String entCode;
//ip
private String ip;
//端口
private Integer port;
}

View File

@ -0,0 +1,48 @@
package com.zhiLian.vehicle.datasource.util;
import com.alibaba.druid.pool.DruidDataSource;
import com.zhiLian.vehicle.datasource.ManyDataSource;
import com.zhiLian.vehicle.datasource.config.factory.DruidDataSourceFactory;
import com.zhiLian.vehicle.datasource.domain.DataSourceInfo;
import com.zhiLian.vehicle.datasource.config.role.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
/**
* @Description:
* @Author Dongzl
* @Date 2022/8/18 17:20
*
*/
@Slf4j
@Component
public class DataSourceService {
@Autowired
private ManyDataSource druidConfig;
@Autowired
private DruidDataSourceFactory druidDataSourceFactory;
@Resource
private DynamicDataSource dynamicDataSource;
public void addDataSource(DataSourceInfo dataSourceInfo){
addDefineDynamicDataSource(druidDataSourceFactory.create(dataSourceInfo), dataSourceInfo.getKey());
}
/**
* @Description: map
* @Author Dongzl
*/
public void addDefineDynamicDataSource(DruidDataSource druidDataSource, String dataSourceName){
Map<Object, Object> defineTargetDataSources = dynamicDataSource.getDefineTargetDataSources();
defineTargetDataSources.put(dataSourceName, druidDataSource);
dynamicDataSource.setTargetDataSources(defineTargetDataSources);
dynamicDataSource.afterPropertiesSet();
}
}

View File

@ -18,8 +18,14 @@ import lombok.ToString;
@NoArgsConstructor
@ToString
public class Path {
private String Q;
private String R;
private String lng;
private String lat;
}