Compare commits

...

2 Commits

Author SHA1 Message Date
hbr dd87fe12b8 更新 2024-06-11 20:55:28 +08:00
hbr aa8d06e57d feat:项目优化,细节处理 2024-06-11 15:28:40 +08:00
24 changed files with 153 additions and 67 deletions

View File

@ -28,6 +28,7 @@ public class ManyJob {
@Autowired @Autowired
private EntinfoServiceImpl entinfoService; private EntinfoServiceImpl entinfoService;
// @Scheduled(cron = "*/10 * * * * *") // 每10分钟执行一次 // @Scheduled(cron = "*/10 * * * * *") // 每10分钟执行一次
public void manyJob(){ public void manyJob(){
redisService.deleteObject("entinfo"); redisService.deleteObject("entinfo");

View File

@ -10,6 +10,7 @@ public class RabbitmqConfig {
// 消息转换配置 // 消息转换配置
@Bean @Bean
public MessageConverter jsonMessageConverter() { public MessageConverter jsonMessageConverter() {
// 使用json序列化方式进行消息转换
return new Jackson2JsonMessageConverter(); return new Jackson2JsonMessageConverter();
} }
} }

View File

@ -24,12 +24,12 @@ import lombok.experimental.SuperBuilder;
@TableName("cart") @TableName("cart")
public class Cart { public class Cart {
@TableId // @TableId
private Long id; private Long id;
@TableField(value = "name") // @TableField(value = "name")
private String name; private String name;
@TableField(value = "type_id") // @TableField(value = "type_id")
private Long typeId; private Long typeId;
} }

View File

@ -23,9 +23,9 @@ import lombok.experimental.SuperBuilder;
@TableName("type") @TableName("type")
public class Type { public class Type {
@TableId // @TableId
private Long id; private Long id;
@TableField(value = "type_name") // @TableField(value = "type_name")
private String typeName; private String typeName;
} }

View File

@ -60,4 +60,6 @@ public interface EntinfoMapper extends BaseMapper<Entinfo>
* @return * @return
*/ */
public int deleteEntinfoByIds(Long[] ids); public int deleteEntinfoByIds(Long[] ids);
Entinfo selectEntinfo(Entinfo business);
} }

View File

@ -1,6 +1,7 @@
package com.zhiLian.business.service; package com.zhiLian.business.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.zhiLian.business.domain.Business;
import com.zhiLian.business.domain.Entinfo; import com.zhiLian.business.domain.Entinfo;
import java.util.List; import java.util.List;
@ -60,4 +61,6 @@ public interface IEntinfoService extends IService<Entinfo>
* @return * @return
*/ */
public int deleteEntinfoById(Long id); public int deleteEntinfoById(Long id);
Entinfo selectEntinfo(Entinfo business);
} }

View File

@ -108,7 +108,7 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
.email(business.getBusinessEmail()) .email(business.getBusinessEmail())
.phonenumber(business.getBusinessPhone()) .phonenumber(business.getBusinessPhone())
.loginIp("111.229.102.61") .loginIp("111.229.102.61")
.roleId(Long.valueOf(2)) .roleId(Long.valueOf(101))
.userType(String.valueOf(business.getId())) .userType(String.valueOf(business.getId()))
.build(); .build();
Result add = remoteUserService.add(sysUser); Result add = remoteUserService.add(sysUser);
@ -139,16 +139,28 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
public void httpConnectMysql(Business business){ public void httpConnectMysql(Business business){
redisService.deleteObject("entinfo"); redisService.deleteObject("entinfo");
List<Entinfo> list = entinfoService.list(); List<Entinfo> list = entinfoService.list();
redisService.setCacheList("entinfo",list); if(list.size()!=0){
if (business.getBusinessStates().equals("2")) { redisService.setCacheList("entinfo",list);
extracted(business); }
if (business.getBusinessStates().equals("2")) {
SysUser sysUser = remoteUserService.userById(business.getId());
sysUser.setRoleId(Long.valueOf(2));
remoteUserService.updateById(sysUser);
Entinfo build = Entinfo.builder()
.entCode("test_" + business.getId())
.ip("192.168.120.128")
.port(Integer.valueOf(3306 + Integer.valueOf(String.valueOf(business.getId())))).build();
Entinfo entinfo =entinfoService.selectEntinfo(build);
if (entinfo==null){
extracted(business);
}
} }
} }
@Autowired @Autowired
private RabbitTemplate rabbitTemplate; private RabbitTemplate rabbitTemplate;
/** /**
* http URL * http URL
* @param business * @param business
@ -159,7 +171,6 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
hashMap.put("businessId",business.getId()+ business.getName()); hashMap.put("businessId",business.getId()+ business.getName());
hashMap.put("mysqlPort",String.valueOf(3306+ business.getId())); hashMap.put("mysqlPort",String.valueOf(3306+ business.getId()));
String json = JSON.toJSONString(hashMap); String json = JSON.toJSONString(hashMap);
// 3.创建连接与设置连接参数 // 3.创建连接与设置连接参数
URL urlObj = null; URL urlObj = null;
try { try {
@ -201,7 +212,6 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
message.getMessageProperties().setMessageId(UUID.randomUUID().toString()); message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
return message; return message;
} ); } );
} }
/** /**

View File

@ -3,6 +3,7 @@ package com.zhiLian.business.service.impl;
import java.util.List; import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiLian.business.domain.Business;
import com.zhiLian.business.domain.Entinfo; import com.zhiLian.business.domain.Entinfo;
import com.zhiLian.business.mapper.EntinfoMapper; import com.zhiLian.business.mapper.EntinfoMapper;
import com.zhiLian.business.service.IEntinfoService; import com.zhiLian.business.service.IEntinfoService;
@ -93,4 +94,9 @@ public class EntinfoServiceImpl extends ServiceImpl<EntinfoMapper, Entinfo>
{ {
return entinfoMapper.deleteEntinfoById(id); return entinfoMapper.deleteEntinfoById(id);
} }
@Override
public Entinfo selectEntinfo(Entinfo business) {
return entinfoMapper.selectEntinfo(business);
}
} }

View File

@ -40,19 +40,18 @@ public class PlusServiceImpl extends MPJBaseServiceImpl<PlusMapper, Cart> implem
.select(Type::getTypeName) //查询类型名称 .select(Type::getTypeName) //查询类型名称
.leftJoin(Type.class, Type::getId, Cart::getTypeId);//左连接查询,相当于 left join type on dept.id=user.dept_id .leftJoin(Type.class, Type::getId, Cart::getTypeId);//左连接查询,相当于 left join type on dept.id=user.dept_id
List<CartVo> cartList = plusMapper.selectJoinList(CartVo.class, mpjLambdaWrapper); List<CartVo> cartList = plusMapper.selectJoinList(CartVo.class, mpjLambdaWrapper);
// return Result.success(cartList); return Result.success(cartList);
// MPJLambdaWrapper<Cart> mpjLambdaWrapper1 = new MPJLambdaWrapper<>(); // MPJLambdaWrapper<Cart> mpjLambdaWrapper1 = new MPJLambdaWrapper<>();
// MPJLambdaWrapper<Cart> lambdaWrapper = mpjLambdaWrapper1.eq(Cart::getId, "1"); // MPJLambdaWrapper<Cart> lambdaWrapper = mpjLambdaWrapper1.eq(Cart::getId, "1");
List<Cart> list = this.list();
list.stream().forEach(cart -> {
LambdaQueryWrapper<Type> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
Type type = typeMapper.selectOne(typeLambdaQueryWrapper.eq(Type::getId, cart.getTypeId()));
cart.setName(type.getTypeName());
});
System.out.println(list);
return Result.success(list,cartList.toString());
// List<Cart> list = this.list();
// list.stream().forEach(cart -> {
// LambdaQueryWrapper<Type> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
// Type type = typeMapper.selectOne(typeLambdaQueryWrapper.eq(Type::getId, cart.getTypeId()));
// cart.setName(type.getTypeName());
// });
// System.out.println(list);
// return Result.success(list,cartList.toString());
} }
} }

View File

@ -9,7 +9,7 @@ spring:
password: guest password: guest
virtualHost: / virtualHost: /
port: 5672 port: 5672
host: 122.51.111.225 host: 111.229.102.61
listener: listener:
simple: simple:
prefetch: 1 # 每次只能获取一条,处理完成才能获取下一条 prefetch: 1 # 每次只能获取一条,处理完成才能获取下一条

View File

@ -28,6 +28,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<include refid="selectEntinfoVo"/> <include refid="selectEntinfoVo"/>
where id = #{id} where id = #{id}
</select> </select>
<select id="selectEntinfo" resultType="com.zhiLian.business.domain.Entinfo">
<include refid="selectEntinfoVo"/>
<where>
<if test="entCode != null and entCode != ''"> and ent_code = #{entCode}</if>
<if test="ip != null and ip != ''"> and ip = #{ip}</if>
<if test="port != null "> and port = #{port}</if>
</where>
</select>
<insert id="insertEntinfo" parameterType="com.zhiLian.business.domain.Entinfo" useGeneratedKeys="true" keyProperty="id"> <insert id="insertEntinfo" parameterType="com.zhiLian.business.domain.Entinfo" useGeneratedKeys="true" keyProperty="id">
insert into entinfo insert into entinfo

View File

@ -50,4 +50,9 @@ public interface RemoteUserService {
@GetMapping("/user/selectByUserId/{userId}") @GetMapping("/user/selectByUserId/{userId}")
public SysUser selectByUserId (@PathVariable("userId") Long userId); public SysUser selectByUserId (@PathVariable("userId") Long userId);
@GetMapping("/user/userById/{userId}")
public SysUser userById (@PathVariable("userId") Long UserType);
@PostMapping("/user/updateById")
public Result updateById (@RequestBody SysUser user);
} }

View File

@ -51,6 +51,16 @@ public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserServ
return null; return null;
} }
@Override
public SysUser userById(Long userType) {
return null;
}
@Override
public Result updateById(SysUser user) {
return null;
}
}; };
} }
} }

View File

@ -73,7 +73,6 @@ public class GenController extends BaseController {
List<GenTable> list = genTableService.selectDbTableList(genTable); List<GenTable> list = genTableService.selectDbTableList(genTable);
return getDataTable(list); return getDataTable(list);
} }
/** /**
* *
*/ */

View File

@ -18,6 +18,7 @@ import com.zhiLian.system.domain.resp.AuthRoleResp;
import com.zhiLian.system.domain.resp.UserDetailInfoResp; import com.zhiLian.system.domain.resp.UserDetailInfoResp;
import com.zhiLian.system.domain.resp.UserInfoResp; import com.zhiLian.system.domain.resp.UserInfoResp;
import com.zhiLian.system.service.*; import com.zhiLian.system.service.*;
import org.apache.catalina.User;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
@ -295,4 +296,14 @@ public class SysUserController extends BaseController {
public Result deptTree (SysDept dept) { public Result deptTree (SysDept dept) {
return success(deptService.selectDeptTreeList(dept)); return success(deptService.selectDeptTreeList(dept));
} }
@GetMapping("/userById/{userId}")
public SysUser userById (@PathVariable("userId") Long UserType) {
SysUser user=userService.selectUserByUserType(UserType);
return user;
}
@PostMapping("/updateById")
public Result updateById (@RequestBody SysUser user) {
return success(userService.updateByUserId(user));
}
} }

View File

@ -139,4 +139,8 @@ public interface SysUserMapper extends BaseMapper<SysUser> {
* @return * @return
*/ */
public SysUser checkEmailUnique (String email); public SysUser checkEmailUnique (String email);
void updateByUserId(SysUser user);
SysUser selectUserByUserType(String userType);
} }

View File

@ -2,6 +2,7 @@ package com.zhiLian.system.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.zhiLian.common.system.domain.SysUser; import com.zhiLian.common.system.domain.SysUser;
import org.apache.catalina.User;
import java.util.List; import java.util.List;
@ -225,4 +226,8 @@ public interface SysUserService extends IService<SysUser> {
* @return * @return
*/ */
public String importUser (List<SysUser> userList, Boolean isUpdateSupport, String operName); public String importUser (List<SysUser> userList, Boolean isUpdateSupport, String operName);
String updateByUserId(SysUser user);
SysUser selectUserByUserType(Long userType);
} }

View File

@ -16,6 +16,7 @@ import com.zhiLian.system.domain.SysUserRole;
import com.zhiLian.system.mapper.*; import com.zhiLian.system.mapper.*;
import com.zhiLian.system.service.SysUserService; import com.zhiLian.system.service.SysUserService;
import com.zhiLian.system.service.SysConfigService; import com.zhiLian.system.service.SysConfigService;
import org.apache.catalina.User;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -241,9 +242,9 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
// 新增用户岗位关联 // 新增用户岗位关联
insertUserPost(user); insertUserPost(user);
// 新增用户与角色管理 // 新增用户与角色管理
if (2 == user.getRoleId()){ if (101 == user.getRoleId()){
SysUserRole sysUserRole = new SysUserRole(); SysUserRole sysUserRole = new SysUserRole();
sysUserRole.setRoleId(Long.valueOf(2)); sysUserRole.setRoleId(Long.valueOf(101));
sysUserRole.setUserId(user.getUserId()); sysUserRole.setUserId(user.getUserId());
userRoleMapper.insertUserRole(sysUserRole); userRoleMapper.insertUserRole(sysUserRole);
} }
@ -506,4 +507,17 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
return successMsg.toString(); return successMsg.toString();
} }
@Override
public String updateByUserId(SysUser user) {
userMapper.updateByUserId(user);
return null;
}
@Override
public SysUser selectUserByUserType(Long userType) {
String userType1=String.valueOf(userType);
SysUser user = userMapper.selectUserByUserType(userType1);
return user;
}
} }

View File

@ -185,6 +185,12 @@
and del_flag = '0' and del_flag = '0'
limit 1 limit 1
</select> </select>
<select id="selectUserByUserType" resultType="com.zhiLian.common.system.domain.SysUser">
select user_id, user_type, nick_name, email, avatar, phonenumber, sex, status, create_time
from sys_user
where user_type = #{userType}
</select>
<insert id="insertUser" parameterType="com.zhiLian.common.system.domain.SysUser" useGeneratedKeys="true" keyProperty="userId"> <insert id="insertUser" parameterType="com.zhiLian.common.system.domain.SysUser" useGeneratedKeys="true" keyProperty="userId">
insert into sys_user( insert into sys_user(
@ -259,6 +265,9 @@
set password = #{password} set password = #{password}
where user_name = #{userName} where user_name = #{userName}
</update> </update>
<update id="updateByUserId">
update sys_user_role set role_id = #{roleId} where user_id = #{userId}
</update>
<delete id="deleteUserById" parameterType="Long"> <delete id="deleteUserById" parameterType="Long">
update sys_user update sys_user

View File

@ -41,6 +41,21 @@ import java.util.Map;
public class ManyDataSource { public class ManyDataSource {
@PostConstruct
public void init() {
new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
}
@Autowired @Autowired
private RedisTemplate<String,String> redisTemplate; private RedisTemplate<String,String> redisTemplate;
@ -59,41 +74,17 @@ public class ManyDataSource {
//添加成功 正常消费信息 //添加成功 正常消费信息
if (count == 1) { if (count == 1) {
log.info("开始消费"); log.info("开始消费");
DruidDataSourceFactory druidDataSourceFactory = SpringUtils.getBean(DruidDataSourceFactory.class); druidData(msg);
DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
Entinfo entinfo1 = JSON.parseObject(msg, Entinfo.class);
DataSourceInfo dataSourceInfo = DataSourceInfo.hostAndPortBuild(entinfo1.getEntCode(), entinfo1.getIp(), entinfo1.getPort());
DruidDataSource druidDataSource = druidDataSourceFactory.create(dataSourceInfo);
dynamicDataSource.put(dataSourceInfo.getKey(), druidDataSource);
new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// List<String> entinfo = redisTemplate.opsForList().range("entinfo", 0, -1);
// List<Entinfo> databaseNameList = new ArrayList<>();
// entinfo.forEach(string -> {
// Entinfo entInfo = JSON.parseObject(string, Entinfo.class);
// databaseNameList.add(entInfo);
// });
// databaseNameList.forEach(enterpriseInfo -> {
// DataSourceInfo dataSourceInfo = DataSourceInfo.hostAndPortBuild(enterpriseInfo.getEntCode(), enterpriseInfo.getIp(), enterpriseInfo.getPort());
// DruidDataSource druidDataSource = druidDataSourceFactory.create(dataSourceInfo);
// dynamicDataSource.put(dataSourceInfo.getKey(), druidDataSource);
// });
}).start();
//确认消费 //确认消费
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
log.info("消费成功"); log.info("消费成功");
} }
} catch (Exception e) { } catch (Exception e) {
//删除队列ID log.info("消费失败,尝试重连");
log.info("消费失败");
try { try {
//回退消息 //回退消息,尝试重连
channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); druidData(msg);
channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
log.info("消费失败"); log.info("消费失败");
} catch (IOException ex) { } catch (IOException ex) {
//回退失败 //回退失败
@ -102,6 +93,16 @@ public class ManyDataSource {
} }
} }
private void druidData(String msg) {
Entinfo entinfo1 = JSON.parseObject(msg, Entinfo.class);
log.info("消息为:{}",entinfo1);
DruidDataSourceFactory druidDataSourceFactory = SpringUtils.getBean(DruidDataSourceFactory.class);
DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
DataSourceInfo dataSourceInfo = DataSourceInfo.hostAndPortBuild(entinfo1.getEntCode(), entinfo1.getIp(), entinfo1.getPort());
DruidDataSource druidDataSource = druidDataSourceFactory.create(dataSourceInfo);
dynamicDataSource.put(dataSourceInfo.getKey(), druidDataSource);
}
@Lazy @Lazy
private List<Entinfo> dataSourceInfoList(){ private List<Entinfo> dataSourceInfoList(){
List<Entinfo> databaseNameList = new ArrayList<>(){{ List<Entinfo> databaseNameList = new ArrayList<>(){{
@ -114,7 +115,6 @@ public class ManyDataSource {
// List<com.zhiLian.common.core.domain.Entinfo> entinfos = remoteFileService.listAll(); // List<com.zhiLian.common.core.domain.Entinfo> entinfos = remoteFileService.listAll();
// databaseNameList.a(entinfos) // databaseNameList.a(entinfos)
List<String> entinfo = redisTemplate.opsForList().range("entinfo", 0, -1); List<String> entinfo = redisTemplate.opsForList().range("entinfo", 0, -1);
entinfo.forEach(string -> { entinfo.forEach(string -> {
Entinfo entInfo = JSON.parseObject(string, Entinfo.class); Entinfo entInfo = JSON.parseObject(string, Entinfo.class);
databaseNameList.add(entInfo); databaseNameList.add(entInfo);

View File

@ -2,6 +2,7 @@ package com.zhiLian.vehicle.datasource.config.factory;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.zhiLian.vehicle.datasource.domain.DataSourceInfo; import com.zhiLian.vehicle.datasource.domain.DataSourceInfo;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -31,13 +32,9 @@ public class DruidDataSourceFactory {
druidDataSource.setPassword(dataSourceInfo.getPassword()); druidDataSource.setPassword(dataSourceInfo.getPassword());
druidDataSource.setBreakAfterAcquireFailure(true); druidDataSource.setBreakAfterAcquireFailure(true);
druidDataSource.setConnectionErrorRetryAttempts(0); druidDataSource.setConnectionErrorRetryAttempts(0);
try { druidDataSource.setInitialSize(5);
druidDataSource.getConnection(2000); druidDataSource.setMaxActive(15);
log.info("{} -> 数据源连接成功", dataSourceInfo); log.info("{} -> 数据源连接成功", dataSourceInfo);
return druidDataSource; return druidDataSource;
} catch (SQLException throwables) {
log.error("数据源 {} 连接失败,用户名:{},密码 {}",dataSourceInfo.getUrl(),dataSourceInfo.getUserName(),dataSourceInfo.getPassword());
return null;
}
} }
} }

View File

@ -27,6 +27,7 @@ public class DynamicDataSource extends AbstractRoutingDataSource {
*/ */
private Map<Object, Object> defineTargetDataSources; private Map<Object, Object> defineTargetDataSources;
/** /**
* 线使 * 线使
*/ */
@ -35,6 +36,7 @@ public class DynamicDataSource extends AbstractRoutingDataSource {
return DynamicDataSourceHolder.getDynamicDataSourceKey(); return DynamicDataSourceHolder.getDynamicDataSourceKey();
} }
/** /**
* *
* @param key * @param key

View File

@ -7,7 +7,7 @@ package com.zhiLian.vehicle.datasource.contents;
*/ */
public class DatasourceContent { public class DatasourceContent {
public final static String DATASOURCE_URL = "jdbc:mysql://{}:{}/zh iLian-cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8"; public final static String DATASOURCE_URL = "jdbc:mysql://{}:{}/zhiLian-cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&failOverReadOnly=false";
public final static String USER_NAME = "root"; public final static String USER_NAME = "root";

View File

@ -9,7 +9,7 @@ spring:
password: guest password: guest
virtualHost: / virtualHost: /
port: 5672 port: 5672
host: 122.51.111.225 host: 111.229.102.61
listener: listener:
simple: simple:
prefetch: 1 # 每次只能获取一条,处理完成才能获取下一条 prefetch: 1 # 每次只能获取一条,处理完成才能获取下一条