fast()多数据源

car-ser
王熙朝 2024-06-04 21:36:26 +08:00
parent 15edaa28f1
commit 904481ca38
40 changed files with 1005 additions and 29 deletions

View File

@ -22,19 +22,15 @@ public class Fence {
/**
*
*/
private String fenceType;
/**
*
*/
private Double radius;
private String fenceType = "多边形";
/**
*
*/
private String eventType;
private String eventType = "N";
/**
*
*/
private String staut;
private String staut = "Y";
/**
*
*/

View File

@ -12,6 +12,4 @@ import lombok.ToString;
public class Path {
private String lat;
private String lng;
}

View File

@ -0,0 +1,16 @@
package com.business.common.psvm;
import com.business.common.domain.Path;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Pences {
private Long groupsId;
private List<Path> list;
}

View File

@ -3,10 +3,12 @@ package com.muyu.goods.controller;
import com.business.common.domain.Fence;
import com.business.common.domain.FenceGroups;
import com.business.common.domain.Path;
import com.business.common.psvm.Pences;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.goods.service.IMapService;
import com.muyu.goods.service.impl.MapService;
import org.apache.commons.codec.language.bm.Rule;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -48,17 +50,42 @@ public class MapController extends BaseController {
}
/**
*
*
* @param list
* @return
*/
@PostMapping("getSel")
public Result<Path> getSel(@RequestBody List<Path> list){
public Result getSel(@RequestBody Pences list){
return success(iMapService.getSel(list));
}
@PostMapping("setSel")
public String setSel(Object r){
return iMapService.setSel(r);
/**
*
* @param fenceId
* @return
*/
@PostMapping("deleteFence/{fenceId}")
public Result deleteFence(@PathVariable Long fenceId){
return success(iMapService.deleteFence(fenceId));
}
/**
*
* @param fenceId
* @return
*/
@PostMapping("queryFence/{fenceId}")
public Result<Fence> queryFence(@PathVariable Long fenceId){
return success(iMapService.queryFence(fenceId));
}
/**
*
* @param fenceId
* @return
*/
@PostMapping("updateFence/{fenceId}")
public Result updateFence(@PathVariable Long fenceId) {
return success(iMapService.updateFence(fenceId));
}
}

View File

@ -12,4 +12,12 @@ public interface MapMapper {
List<FenceGroups> selectFenceGroups();
List<Fence> selectFence();
int indexFence(Fence fence);
int deleteFence(@Param("fenceId") Long fenceId);
Fence queryFence(@Param("fenceId") Long fenceId);
int updateFence(@Param("fenceId") Long fenceId, @Param("status") String status);
}

View File

@ -3,7 +3,9 @@ package com.muyu.goods.service;
import com.business.common.domain.Fence;
import com.business.common.domain.FenceGroups;
import com.business.common.domain.Path;
import com.business.common.psvm.Pences;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@ -15,7 +17,11 @@ public interface IMapService {
FenceGroups selectFenceGroupsById(Long carId);
List<Path> getSel(List<Path> list);
String getSel(Pences list);
String setSel(Object r);
String deleteFence(Long fenceId);
Fence queryFence(Long fenceId);
String updateFence(Long fenceId);
}

View File

@ -79,6 +79,7 @@ public class CarServiceImpl implements ICarService
int i = carMapper.insertCar(car);
if (i>0) {
Car car1 = carMapper.carByCar();
System.out.println(car1);
mapMapper.indexFenceGroups(car1.getCarId(),"car"+car1.getCarId());
}
return i;

View File

@ -1,15 +1,18 @@
package com.muyu.goods.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.business.common.domain.Fence;
import com.business.common.domain.FenceGroups;
import com.business.common.domain.Path;
import com.business.common.psvm.Pences;
import com.muyu.goods.mapper.MapMapper;
import com.muyu.goods.service.IMapService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
import java.util.stream.Collectors;
@ -29,7 +32,6 @@ public class MapService implements IMapService {
List<Fence> fenceList = selectFence().stream().filter(fa -> fa.getGroupId() == fenceGroups.getGroupsId()).collect(Collectors.toList());
fenceGroups.setFenceList(fenceList);
}
System.out.println(fenceGroupsList);
return fenceGroupsList;
}
@ -46,10 +48,52 @@ public class MapService implements IMapService {
}
@Override
public List<Path> getSel(List<Path> list) {
System.out.println(list);
String jsonString = JSONObject.toJSONString(list);
Path path = JSONObject.parseObject(jsonString, Path.class);
return null;
public String getSel(Pences pences) {
System.out.println(pences);
if (pences.getGroupsId() == null){
return "数据不全";
}
FenceGroups fenceGroups = selectFenceGroups().stream().filter(g -> g.getGroupsId() == pences.getGroupsId()).collect(Collectors.toList()).get(0);
Fence fence = new Fence();
fence.setGroupId(pences.getGroupsId());
List<Path> list = pences.getList();
String jsonString = JSONArray.toJSONString(list);
fence.setPolygonPoints(jsonString);
List<Path> paths = JSONArray.parseArray(jsonString, Path.class);
fence.setFenceName("围栏"+ (fenceGroups.getFenceList().size()+1));
int i = mapMapper.indexFence(fence);
if (i> 0) {
return "传入电子围栏";
}
return "传入电子围栏失败";
}
@Override
public String deleteFence(Long fenceId) {
int i = mapMapper.deleteFence(fenceId);
if (i>0){
return "完成";
}
return "无效";
}
@Override
public Fence queryFence(Long fenceId) {
return mapMapper.queryFence(fenceId);
}
@Override
public String updateFence(Long fenceId) {
Fence fence = queryFence(fenceId);
int i = 0;
if (fence.getStaut().equals("Y")){
i = mapMapper.updateFence(fenceId,"N");
}else {
i = mapMapper.updateFence(fenceId,"Y");
}
if (i>0){
return "成功";
}
return "失败";
}
}

View File

@ -25,4 +25,4 @@ spring:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
logging:
level:
com.muyu.system.mapper: DEBUG
com.muyu.rule.mapper: DEBUG

View File

@ -44,7 +44,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select>
<select id="carByCar" resultType="com.business.common.domain.Car">
<include refid="selectCarVo"></include>
ORDER BY id DESC LIMIT 1;
ORDER BY car_id DESC LIMIT 1;
</select>
<insert id="insertCar" parameterType="com.business.common.domain.Car" useGeneratedKeys="true" keyProperty="carId">

View File

@ -15,9 +15,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="groupId" column="group_id" />
<result property="fenceName" column="fence_name" />
<result property="fenceType" column="fence_type" />
<result property="radius" column="radius" />
<result property="eventType" column="event_type" />
<result property="status" column="status" />
<result property="staut" column="staut" />
<result property="polygonPoints" column="polygon_points" />
</resultMap>
@ -26,18 +25,51 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</sql>
<sql id="FencesVo">
select fence_id, group_id, fence_name, fence_type, radius, event_type, staut, polygon_points from fence
select fence_id, group_id, fence_name, fence_type, event_type, staut, polygon_points from fence
</sql>
<insert id="indexFenceGroups">
insert into fence_groups ( groups_id, car_id, groups_name )
values (0,#{carId},#{groupsName});
</insert>
<insert id="indexFence">
insert into fence
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="groupId != null">group_id,</if>
<if test="fenceName != null">fence_name,</if>
<if test="fenceType != null">fence_type,</if>
<if test="eventType != null">event_type,</if>
<if test="staut != null">staut,</if>
<if test="polygonPoints != null">polygon_points,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="groupId != null">#{groupId},</if>
<if test="fenceName != null">#{fenceName},</if>
<if test="fenceType != null">#{fenceType},</if>
<if test="eventType != null">#{eventType},</if>
<if test="staut != null">#{staut},</if>
<if test="polygonPoints != null">#{polygonPoints},</if>
</trim>
</insert>
<update id="updateFence">
update fence
set staut = #{status}
where fence_id = #{fenceId};
</update>
<delete id="deleteFence">
delete
from fence
where fence_id = #{fenceId};
</delete>
<select id="selectFenceGroups" resultType="com.business.common.domain.FenceGroups">
<include refid="FenceGroupsVo"></include>
</select>
<select id="selectFence" resultType="com.business.common.domain.Fence">
<include refid="FencesVo"></include>
</select>
<select id="queryFence" resultType="com.business.common.domain.Fence">
<include refid="FencesVo"></include>
where fence_id = #{fenceId}
</select>
</mapper>

View File

@ -0,0 +1,47 @@
package com.muyu.goods.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
public class Sources {
/**
*
*/
private Long id;
/**
*
*/
private String name;
/**
*
*/
private String url = "ry_goods";
/**
* ip
*/
private String ip;
/**
*
*/
private String username = "root";
/**
*
*/
private String password = "Qq4152637";
public static Sources index(String name,String ip) {
return builder()
.name(name)
.url("ry_goods")
.ip(ip)
.username("root")
.password("Qq4152637")
.build();
}
}

View File

@ -148,4 +148,9 @@ public class EnterpriseController extends BaseController
return success(enterpriseService.getLevel(id,serviceLevel));
}
@PostMapping("bu/{id}")
public Result bu(@PathVariable Long id){
return success(enterpriseService.bu(id));
}
}

View File

@ -2,6 +2,7 @@ package com.muyu.goods.mapper;
import java.util.List;
import com.muyu.goods.domain.Enterprise;
import com.muyu.goods.domain.Sources;
import org.apache.ibatis.annotations.Param;
/**
@ -69,4 +70,5 @@ public interface EnterpriseMapper
int getLevel(@Param("id") Long id, @Param("serviceLevel") Integer serviceLevel);
void indexSources(Sources sources);
}

View File

@ -77,4 +77,6 @@ public interface IEnterpriseService
List<Enterprise> lists();
String getLevel(Long id, Integer serviceLevel);
String bu(Long id);
}

View File

@ -8,6 +8,7 @@ import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.common.system.domain.SysUser;
import com.muyu.goods.domain.Sources;
import com.muyu.goods.pojo.HttpClient;
import com.muyu.system.remote.RemoteSystemManageService;
import muyu.goods.enterprise.client.config.EnterpriseConfig;
@ -77,6 +78,9 @@ public class EnterpriseServiceImpl implements IEnterpriseService
enterpriseConfig.index(enterprise1);
//新建的企业绑定mysql服务
HttpClient.http(enterprise1);
Sources sources = Sources.index("enterprise" + enterprise1.getId(), String.valueOf((int) (enterprise.getId() + 3306)));
System.out.println(sources);
enterpriseMapper.indexSources(sources);
}
return i;
}
@ -106,7 +110,6 @@ public class EnterpriseServiceImpl implements IEnterpriseService
Enterprise enterprise = new Enterprise();
enterprise.setId(id);
enterprise.setAuthenticationDate(DateUtils.getNowDate());
return enterpriseMapper.authentication(enterprise);
}
@ -178,4 +181,18 @@ public class EnterpriseServiceImpl implements IEnterpriseService
}
}
@Override
public String bu(Long id) {
Enterprise enterprise = selectEnterpriseById(id);
//补充企业绑定mysql服务
try {
HttpClient.http(enterprise);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "成功";
}
}

View File

@ -25,4 +25,4 @@ spring:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
logging:
level:
com.muyu.system.mapper: DEBUG
com.muyu.goods.mapper: DEBUG

View File

@ -91,6 +91,23 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
0,
</trim>
</insert>
<insert id="indexSources">
insert into sources
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">name,</if>
<if test="url != null">url,</if>
<if test="ip != null">ip,</if>
<if test="username != null">username,</if>
<if test="password != null">password,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">#{name},</if>
<if test="url != null">#{url},</if>
<if test="ip != null">#{ip},</if>
<if test="username != null">#{username},</if>
<if test="password != null">#{password},</if>
</trim>
</insert>
<update id="updateEnterprise" parameterType="com.muyu.goods.domain.Enterprise">
update enterprise

View File

@ -0,0 +1,112 @@
<?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.muyu</groupId>
<artifactId>muyu</artifactId>
<version>3.6.3</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>muyu-moudels-many-datasource</artifactId>
<description>多数据源</description>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<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>
<!-- MuYu Common DataSource -->
<dependency>
<groupId>com.muyu</groupId>
<artifactId>muyu-common-datasource</artifactId>
</dependency>
<!-- MuYu Common DataScope -->
<dependency>
<groupId>com.muyu</groupId>
<artifactId>muyu-common-datascope</artifactId>
</dependency>
<!-- MuYu Common Log -->
<dependency>
<groupId>com.muyu</groupId>
<artifactId>muyu-common-log</artifactId>
</dependency>
<!-- MuYu Common Swagger -->
<dependency>
<groupId>com.muyu</groupId>
<artifactId>muyu-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,22 @@
package com.muyu.cloud;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.muyu.common.security.annotation.EnableCustomConfig;
import com.muyu.common.security.annotation.EnableMyFeignClients;
import com.muyu.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
*
*/
@EnableCustomConfig
@EnableCustomSwagger2
@EnableMyFeignClients
@SpringBootApplication(exclude = {DynamicDataSourceAutoConfiguration.class, DataSourceAutoConfiguration.class})
public class CloudManyDataSourceApplication {
public static void main(String[] args) {
SpringApplication.run(CloudManyDataSourceApplication.class,args);
}
}

View File

@ -0,0 +1,39 @@
package com.muyu.cloud.common;
import com.muyu.cloud.datasource.DataSourceInfo;
import com.muyu.cloud.datasource.util.DataSourceService;
import com.muyu.cloud.service.CloudService;
import com.muyu.common.core.domain.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Log4j2
@RestController
@RequestMapping("cloud")
public class CloudController {
@Autowired
private CloudService cloudService;
@Autowired
private DataSourceService dataSourceService;
@PostMapping("source")
public Result selSource() {
Object clout = cloudService.selSource();
return Result.success(clout);
}
/**
*
* @param ip
* @return
*/
@PostMapping("/{ip}")
public Result selectIp(@PathVariable String ip){
dataSourceService.addDataSourceIp(DataSourceInfo.dataIpBuild(ip));
return null;
}
}

View File

@ -0,0 +1,51 @@
package com.muyu.cloud.datasource;
import com.muyu.common.core.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import static com.muyu.cloud.datasource.contents.DatasourceContent.*;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:15
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DataSourceInfo {
private String key;
private String ip;
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();
}
public static DataSourceInfo dataIpBuild(String ip) {
return DataSourceInfo.builder()
.ip(ip)
.url(StringUtils.format(DATASOURCE_URL,ip))
.password(PASSWORD)
.userName(USER_NAME)
.build();
}
}

View File

@ -0,0 +1,51 @@
package com.muyu.cloud.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;
}
/**
* 使ip
*/
public static String getDynamicDataSourceIp(){
String ip = DYNAMIC_DATASOURCE_KEY.get();
Assert.notNull(ip, "请携带数据标识");
return ip;
}
/**
*
*/
public static void removeDynamicDataSourceKey(){
log.info("移除数据源:{}",DYNAMIC_DATASOURCE_KEY.get());
DYNAMIC_DATASOURCE_KEY.remove();
}
}

View File

@ -0,0 +1,46 @@
package com.muyu.cloud.datasource.config;
import com.muyu.cloud.datasource.DynamicDataSourceHolder;
import com.muyu.common.security.utils.SecurityUtils;
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.muyu.cloud.common.*Controller.*(..))")
public void pointcut () {
}
/**
*
*/
@Before("pointcut()")
public void beforeMethod() {
// Long storeId = SecurityUtils.getLoginUser().getSysUser().getUserId();
// DynamicDataSourceHolder.setDynamicDataSourceKey("test_"+storeId);
}
/**
*
*
*
*/
@After("pointcut()")
public void afterMethod() {
DynamicDataSourceHolder.removeDynamicDataSourceKey();
}
}

View File

@ -0,0 +1,74 @@
package com.muyu.cloud.datasource.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.muyu.cloud.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 {
/**
*
* @return
*/
private List<DataSourceInfo> getDataSourceInfoList(){
List<String> databaseNameList = new ArrayList<>(){{
add("3310");
add("3311");
}};
return databaseNameList.stream().map(DataSourceInfo::dataIpBuild).toList();
}
/**
* @Description:
* @Author Dongzl
*/
public DruidDataSource createDataSourceConnection(DataSourceInfo dataSourceInfo) {
DruidDataSource druidDataSource = new DruidDataSource();//配置连接池
druidDataSource.setUrl(dataSourceInfo.getUrl());//配置数据库的连接url
druidDataSource.setUsername(dataSourceInfo.getUserName());//配置用户名
druidDataSource.setPassword(dataSourceInfo.getPassword());//配置密码
druidDataSource.setBreakAfterAcquireFailure(true);//配置
druidDataSource.setConnectionErrorRetryAttempts(0);//配置
try {
druidDataSource.getConnection(2000);
log.info("{} -> 数据源连接成功", dataSourceInfo.getIp());
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,33 @@
package com.muyu.cloud.datasource.config;
import com.muyu.cloud.datasource.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
*/
@EqualsAndHashCode(callSuper = true)
@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,12 @@
package com.muyu.cloud.datasource.config.factory;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
/**
*
*/
@Component
@Log4j2
public class DruidDataSourceFactory {
}

View File

@ -0,0 +1,51 @@
package com.muyu.cloud.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;
}
/**
* 使ip
*/
public static String getDynamicDataSourceIp(){
String ip = DYNAMIC_DATASOURCE_KEY.get();
Assert.notNull(ip, "请携带数据标识");
return ip;
}
/**
*
*/
public static void removeDynamicDataSourceKey(){
log.info("移除数据源:{}",DYNAMIC_DATASOURCE_KEY.get());
DYNAMIC_DATASOURCE_KEY.remove();
}
}

View File

@ -0,0 +1,33 @@
package com.muyu.cloud.datasource.config.role;
import com.muyu.cloud.datasource.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
*/
@EqualsAndHashCode(callSuper = true)
@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.muyu.cloud.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.muyu.cloud.datasource.contents;
/**
* @author DongZl
* @description:
* @Date 2023-8-1 11:02
*/
public class DatasourceContent {
public final static String DATASOURCE_URL = "jdbc:mysql://129.211.23.219:{}/ry_goods?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
public final static String USER_NAME = "root";
public final static String PASSWORD = "Qq4152637";
}

View File

@ -0,0 +1,58 @@
package com.muyu.cloud.datasource.util;
import com.alibaba.druid.pool.DruidDataSource;
import com.muyu.cloud.datasource.DataSourceInfo;
import com.muyu.cloud.datasource.config.DruidConfig;
import com.muyu.cloud.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;
/**
*
* @param dataSourceInfo
*/
public void addDataSource(DataSourceInfo dataSourceInfo){
//获取数据源连接请求
addDefineDynamicDataSource(druidConfig.createDataSourceConnection(dataSourceInfo), dataSourceInfo.getKey());
}
/**
*
* @param dataSourceInfo
*/
public void addDataSourceIp(DataSourceInfo dataSourceInfo){
//获取数据源连接请求
addDefineDynamicDataSource(druidConfig.createDataSourceConnection(dataSourceInfo), dataSourceInfo.getIp());
}
/**
* @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,8 @@
package com.muyu.cloud.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CloudMapper {
Object selSource();
}

View File

@ -0,0 +1,5 @@
package com.muyu.cloud.service;
public interface CloudService {
Object selSource();
}

View File

@ -0,0 +1,16 @@
package com.muyu.cloud.service.impl;
import com.muyu.cloud.mapper.CloudMapper;
import com.muyu.cloud.service.CloudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CloudServiceImpl implements CloudService {
@Autowired
private CloudMapper cloudMapper;
@Override
public Object selSource() {
return cloudMapper.selSource();
}
}

View File

@ -0,0 +1,28 @@
# Tomcat
server:
port: 9209
# Spring
spring:
application:
# 应用名称
name: muyu-range
profiles:
# 环境配置
active: dev
cloud:
nacos:
discovery:
# 服务注册地址
server-addr: 129.211.23.219:8848
config:
# 配置中心地址
server-addr: 129.211.23.219:8848
# 配置文件格式
file-extension: yml
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
logging:
level:
com.muyu.cloud.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/muyu-moudels-many-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.muyu" 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

@ -0,0 +1,11 @@
<?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="com.muyu.cloud.mapper.CloudMapper">
<select id="selSource" resultType="java.lang.Object">
select * from status
</select>
</mapper>

View File

@ -217,6 +217,7 @@
<module>muyu-common</module>
<module>muyu-modules/muyu-goods-enterprise</module>
<module>muyu-modules/muyu-business</module>
<module>muyu-modules/muyu-moudels-many-datasource</module>
</modules>
<packaging>pom</packaging>