Compare commits

...

54 Commits

Author SHA1 Message Date
ywt 08d79266ed feat(): 优化创建实例将查询到的实例ID存储到redis,优化启动车辆,将车辆信息发送到rabbitmq中 2024-10-10 19:07:38 +08:00
ywt ed3830c1ae feat(): 车辆上线将车辆信息发送到消息队列 2024-10-09 21:47:25 +08:00
ywt edeeb878c5 feat(): 创建实例,将实例缓存到redis中,测试轮询 2024-10-09 14:05:43 +08:00
ywt 27479e2b49 feat(): 重构创建实例代码以及删除 2024-10-08 10:43:19 +08:00
sy200 51ca5ef6f4 feat:()修改策略信息存储方法 2024-10-08 08:49:30 +08:00
晨哀 2695602972 Merge remote-tracking branch 'origin/dev' into dev 2024-10-07 18:37:40 +08:00
sy200 eb5960822e feat:()修改车辆列表方法 2024-10-07 18:33:41 +08:00
ywt 620decf638 Merge branch 'dev.gateway.aliyuninitecs' into dev 2024-10-07 16:12:06 +08:00
ywt bfa5391ae1 feat(): 三次修改rabbitmq配置 2024-10-07 16:11:37 +08:00
ywt 3629d522bb Merge remote-tracking branch 'origin/dev' into dev 2024-10-07 14:33:58 +08:00
sy200 d2462e6456 feat:()修改存列表方法 2024-10-07 14:31:56 +08:00
sy200 d2b29e6323 feat:()修改报错 2024-10-07 12:11:58 +08:00
sy200 afdcc48a42 Merge branch 'dev.server' into dev
# Conflicts:
#	cloud-modules/cloud-modules-enterprise/cloud-modules-enterprise-server/src/main/java/com/muyu/enterprise/controller/VehicleController.java
#	cloud-modules/cloud-modules-protocol-parsing/src/main/java/com/muyu/cloud/protocol/parsing/test/ParsingTest.java
2024-10-07 12:07:02 +08:00
sy200 74739614e5 feat:()修改存报文模版的方法 2024-10-07 12:01:41 +08:00
李东佳 dc4f5bbdcb fix():解决报错 2024-10-07 11:45:44 +08:00
sy200 9e1f941be5 feat:()查看车辆绑定围栏组的信息 2024-10-07 11:15:26 +08:00
ywt 689a630024 Merge branch 'dev.gateway.aliyuninitecs' into dev 2024-10-07 10:49:19 +08:00
ywt 8ac2d539f4 feat(): 二次修改rabbitmq配置 2024-10-07 10:48:59 +08:00
ywt 75f8da414d Merge branch 'dev.gateway.aliyuninitecs' into dev 2024-10-07 10:30:26 +08:00
ywt 6903066127 Merge remote-tracking branch 'origin/dev' into dev 2024-10-07 10:30:17 +08:00
ywt c5de9a5bed feat(): 修改rabbitmq配置 2024-10-07 10:29:50 +08:00
晨哀 edb3e74824 Merge remote-tracking branch 'origin/dev.processing' into dev 2024-10-07 10:16:28 +08:00
晨哀 2430d10401 feat:() 新增缓存和修改上线下线监听 2024-10-07 10:10:26 +08:00
sy200 929275fd5a Merge remote-tracking branch 'origin/dev' into dev
# Conflicts:
#	cloud-modules/cloud-modules-enterprise/cloud-modules-enterprise-cache/src/main/java/com/muyu/enterprise/cache/AllMessageValueCacheService.java
#	cloud-modules/cloud-modules-enterprise/cloud-modules-enterprise-server/src/main/java/com/muyu/enterprise/controller/VehicleTypeController.java
2024-10-07 09:28:55 +08:00
sy200 802cd54947 Merge branch 'dev.server' into dev 2024-10-07 09:14:35 +08:00
sy200 a00e5345b4 feat:()修改代码方法 2024-10-06 21:20:41 +08:00
ywt 3c1b78218e Merge branch 'dev.gateway.aliyuninitecs' into dev 2024-10-06 15:53:29 +08:00
ywt 849d5328ac feat(): 获取http连接的参数 2024-10-06 15:52:32 +08:00
ywt 152296d63a Merge remote-tracking branch 'origin/dev' into dev 2024-10-06 15:18:06 +08:00
ywt 30560b90cf feat(): 创建实力数量、车辆服务器、返回创建码、车辆鉴权的参数、车辆VIN实体类 2024-10-06 15:17:28 +08:00
sy200 0be090d11b feat:()优化代码 2024-10-06 14:42:13 +08:00
李东佳 b29363a31a feat():更改nacos命名空间 2024-10-06 14:28:52 +08:00
李东佳 3b35565404 feat():删除远程调用方法 2024-10-06 14:17:59 +08:00
李东佳 846a03f75c fix(): 修改报文数据解析获取报文数据模版方法 2024-10-06 09:55:24 +08:00
李东佳 542a656dc6 fix(): 修改报文数据解析获取报文数据模版方法 2024-10-04 22:09:59 +08:00
sy200 832da812c3 feat:()添加列表Redis方法 2024-10-04 20:49:56 +08:00
李东佳 a834f9d1bd fix(): 修改报文数据的缓存方法 2024-10-04 20:46:16 +08:00
李东佳 960d68f72e fix(): 修改报文数据的缓存方法 2024-10-04 20:38:00 +08:00
李东佳 2c5387f048 feat(): 添加车辆类型缓存方法 2024-10-04 20:05:55 +08:00
sy200 f57deada17 Merge branch 'dev.server' into dev 2024-10-04 16:49:03 +08:00
晨哀 eade0c66ea feat:() 新增下线监听和修改上线监听 2024-10-04 16:48:40 +08:00
sy200 ef0311d362 feat:()添加列表Redis方法 2024-10-04 16:43:47 +08:00
晨哀 0a2fc7a9ce feat:() 添加数据库事件 2024-10-04 10:25:26 +08:00
晨哀 98560aacdc feat:() 新增事件监听器 2024-10-04 10:24:43 +08:00
晨哀 4e1790a47c feat:() 新增事件类型,事件监听接口,策略发送事件 2024-10-04 10:24:15 +08:00
晨哀 d02813f7e4 feat:() 新增MQ生产者 和 修改kafka生产者的信息 2024-10-04 10:18:16 +08:00
晨哀 0e391451b0 feat:() 新增iotdb配置文件,iotdb测试 2024-10-04 10:08:23 +08:00
晨哀 f56787b5a8 feat:() 来类加注解 2024-10-04 10:01:38 +08:00
晨哀 7033d0e9dd feat:() 新增MQ配置文件 和 MQ消费者 2024-10-04 10:01:08 +08:00
晨哀 84b54e9116 feat:() 新增MQ和Caffeine缓存库依赖 和 修改配置文件 2024-10-04 09:46:03 +08:00
ywt 5bb0737c82 10.4新建分支 2024-10-04 09:33:54 +08:00
sy200 d1440fb706 feat:()优化代码 2024-10-04 09:13:30 +08:00
sy200 3ed255fe1e feat:()添加报文模版缓存 2024-10-02 14:33:01 +08:00
sy200 1d91e51199 feat:()添加报文模版缓存 2024-10-02 09:40:38 +08:00
107 changed files with 2925 additions and 579 deletions

View File

@ -11,6 +11,9 @@
<artifactId>cloud-common-rabbit</artifactId> <artifactId>cloud-common-rabbit</artifactId>
<description>
cloud-common-rabbit 模块提供RabbitMq消息队列的相关配置
</description>
<properties> <properties>
<maven.compiler.source>17</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>

View File

@ -6,6 +6,7 @@ import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -17,6 +18,7 @@ import java.util.concurrent.TimeUnit;
**/ **/
@SuppressWarnings(value = {"unchecked", "rawtypes"}) @SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component @Component
//@Service
public class RedisService { public class RedisService {
@Autowired @Autowired
public RedisTemplate redisTemplate; public RedisTemplate redisTemplate;

View File

@ -63,4 +63,5 @@ public class LoginUser implements Serializable {
*/ */
private SysUser sysUser; private SysUser sysUser;
} }

View File

@ -0,0 +1,23 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
/**
*
*/
public class AllFaultCacheService extends CacheAbsBacis {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllFault:info:";
}
@Override
public String decode(String key) {
return key.replace("AllFault:info:", "");
}
}

View File

@ -0,0 +1,27 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.Fence;
import com.muyu.domain.req.FenceReq;
import com.muyu.domain.resp.FenceResp;
/**
*
*/
public class AllFenceCahceService extends CacheAbsBacis<String, FenceResp> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllFence:info:";
}
@Override
public String decode(String key) {
return key.replace("AllFence:info:", "");
}
}

View File

@ -0,0 +1,31 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.MessageTemplate;
import com.muyu.domain.MessageValue;
import com.muyu.domain.req.MessageValueReq;
import com.muyu.domain.resp.MessageValueListResp;
import java.util.List;
/**
*
*/
public class AllMessageValueCacheService extends CacheAbsBacis<String, List<MessageValueListResp>> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllMessagevalue:info:";
}
@Override
public String decode(String key) {
return key.replace("AllMessagevalue:info:", "");
}
}

View File

@ -0,0 +1,36 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.Vehicle;
import com.muyu.domain.req.VehicleAddReq;
import com.muyu.domain.req.VehicleManageReq;
import com.muyu.domain.resp.VehicleManageResp;
import java.util.List;
/**
*
*/
public class AllVehicleCacheService extends CacheAbsBacis<String, VehicleManageResp> {
@Override
public void clear() {
}
/**
* key
* @return
*/
@Override
public String keyPre() {
return "AllVehicle:info:";
}
@Override
public String decode(String key) {
return key.replace("AllVehicle:info:", "");
}
}

View File

@ -0,0 +1,24 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.VehicleType;
/**
*
*/
public class AllVehicleTypeCacheService extends CacheAbsBacis<String, VehicleType> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllVehicleType:info:";
}
@Override
public String decode(String key) {
return key.replace("AllVehicleType:info:", "");
}
}

View File

@ -0,0 +1,24 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.WarnRule;
/**
*
*/
public class AllWarnRuleCacheService extends CacheAbsBacis<String, WarnRule> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllWarnRule:info:";
}
@Override
public String decode(String key) {
return key.replace("AllWarnRule:info:", "");
}
}

View File

@ -0,0 +1,27 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.resp.WarnStrategyAndVinResp;
import com.muyu.domain.resp.WarnVehicleResp;
import java.util.List;
/**
*
*/
public class AllWarnStrategyAndVinCacheService extends CacheAbsBacis<String, List<WarnStrategyAndVinResp>> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllWarnStrategy:info:";
}
@Override
public String decode(String key) {
return key.replace("AllWarnStrategy:info:", "");
}
}

View File

@ -0,0 +1,28 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.WarnStrategy;
import com.muyu.domain.resp.WarnStrategyAndVinResp;
import com.muyu.domain.resp.WarnVehicleResp;
import java.util.List;
/**
*
*/
public class AllWarnStrategyCacheService extends CacheAbsBacis<String, WarnVehicleResp> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "AllWarnStrategy:info:";
}
@Override
public String decode(String key) {
return key.replace("AllWarnStrategy:info:", "");
}
}

View File

@ -2,6 +2,9 @@ package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis; import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.Fence; import com.muyu.domain.Fence;
import com.muyu.domain.resp.FenceResp;
import java.util.List;
/** /**
* *
@ -21,4 +24,5 @@ public class FenceCahceService extends CacheAbsBacis<String, Fence> {
public String decode(String key) { public String decode(String key) {
return key.replace("fence:info:", ""); return key.replace("fence:info:", "");
} }
} }

View File

@ -0,0 +1,26 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.MessageTemplate;
/**
*
*/
public class MessageTemplateCacheService extends CacheAbsBacis<String, MessageTemplate> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "messageTemplate:info:";
}
@Override
public String decode(String key) {
return key.replace("messageTemplate:info:", "");
}
}

View File

@ -0,0 +1,26 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.MessageValue;
/**
*
*/
public class MessageValueCacheService extends CacheAbsBacis<String, MessageValue> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "messagevalue:info:";
}
@Override
public String decode(String key) {
return key.replace("messagevalue:info:", "");
}
}

View File

@ -4,7 +4,7 @@ import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.Vehicle; import com.muyu.domain.Vehicle;
/** /**
* *
*/ */
public class VehicleCacheService extends CacheAbsBacis<String, Vehicle> { public class VehicleCacheService extends CacheAbsBacis<String, Vehicle> {

View File

@ -0,0 +1,24 @@
package com.muyu.enterprise.cache;
import com.muyu.common.cache.CacheAbsBacis;
import com.muyu.domain.VehicleType;
/**
*
*/
public class VehicleTypeCacheService extends CacheAbsBacis<String, VehicleType> {
@Override
public void clear() {
}
@Override
public String keyPre() {
return "vehicleType:info:";
}
@Override
public String decode(String key) {
return key.replace("vehicleType:info:", "");
}
}

View File

@ -14,11 +14,11 @@ public class WarnRuleCacheService extends CacheAbsBacis<String, WarnRule> {
@Override @Override
public String keyPre() { public String keyPre() {
return "warn:info:"; return "warnRule:info:";
} }
@Override @Override
public String decode(String key) { public String decode(String key) {
return key.replace("warn:info:", ""); return key.replace("warnRule:info:", "");
} }
} }

View File

@ -5,7 +5,7 @@ import com.muyu.domain.WarnRule;
import com.muyu.domain.WarnStrategy; import com.muyu.domain.WarnStrategy;
/** /**
* *
*/ */
public class WarnStrategyCacheService extends CacheAbsBacis<String, WarnStrategy> { public class WarnStrategyCacheService extends CacheAbsBacis<String, WarnStrategy> {
@Override @Override
@ -15,11 +15,11 @@ public class WarnStrategyCacheService extends CacheAbsBacis<String, WarnStrategy
@Override @Override
public String keyPre() { public String keyPre() {
return "warn:info:"; return "warnStrategy:info:";
} }
@Override @Override
public String decode(String key) { public String decode(String key) {
return key.replace("warn:info:", ""); return key.replace("warnStrategy:info:", "");
} }
} }

View File

@ -1,5 +1,18 @@
com.muyu.enterprise.cache.VehicleCacheService com.muyu.enterprise.cache.AllFaultCacheService
com.muyu.enterprise.cache.AllFenceCahceService
com.muyu.enterprise.cache.AllMessageValueCacheService
com.muyu.enterprise.cache.AllVehicleCacheService
com.muyu.enterprise.cache.AllVehicleTypeCacheService
com.muyu.enterprise.cache.AllWarnRuleCacheService
com.muyu.enterprise.cache.AllWarnStrategyAndVinCacheService
com.muyu.enterprise.cache.AllWarnStrategyCacheService
com.muyu.enterprise.cache.FaultCacheService com.muyu.enterprise.cache.FaultCacheService
com.muyu.enterprise.cache.FenceCahceService com.muyu.enterprise.cache.FenceCahceService
com.muyu.enterprise.cache.MessageTemplateCacheService
com.muyu.enterprise.cache.MessageValueCacheService
com.muyu.enterprise.cache.VehicleCacheService
com.muyu.enterprise.cache.VehicleTypeCacheService
com.muyu.enterprise.cache.WarnRuleCacheService com.muyu.enterprise.cache.WarnRuleCacheService
com.muyu.enterprise.cache.WarnStrategyCacheService com.muyu.enterprise.cache.WarnStrategyCacheService

View File

@ -12,12 +12,7 @@ import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder; import lombok.experimental.SuperBuilder;
/** /**
* @Author: LiDongJia *
* @Package: com.muyu.car.domain
* @Project: 2112-car-cloud-server
* @name: MessageTemplate
* @Date: 2024/9/18 21:11
* @Description:
*/ */
@Data @Data
@SuperBuilder @SuperBuilder

View File

@ -119,6 +119,10 @@ public class Vehicle extends BaseEntity {
@Schema(type = "Integer",description = "电子围栏外键") @Schema(type = "Integer",description = "电子围栏外键")
private Integer fenceGroupId; private Integer fenceGroupId;
/** 策略id */
@Schema(type = "Long",description = "策略id")
private Long warnStrategyId;
public static Vehicle addBuild(VehicleAddReq vehicleAddReq){ public static Vehicle addBuild(VehicleAddReq vehicleAddReq){
return Vehicle.builder() return Vehicle.builder()
.licenceNumber(vehicleAddReq.getLicenceNumber()) .licenceNumber(vehicleAddReq.getLicenceNumber())
@ -132,6 +136,7 @@ public class Vehicle extends BaseEntity {
.vehicleStatus(vehicleAddReq.getVehicleStatus()) .vehicleStatus(vehicleAddReq.getVehicleStatus())
.companyId(vehicleAddReq.getCompanyId()) .companyId(vehicleAddReq.getCompanyId())
.fenceGroupId(vehicleAddReq.getFenceGroupId()) .fenceGroupId(vehicleAddReq.getFenceGroupId())
.warnStrategyId(vehicleAddReq.getWarnStrategyId())
.build(); .build();
} }
@ -149,6 +154,7 @@ public class Vehicle extends BaseEntity {
.vehicleStatus(vehicleUpdReq.getVehicleStatus()) .vehicleStatus(vehicleUpdReq.getVehicleStatus())
.companyId(vehicleUpdReq.getCompanyId()) .companyId(vehicleUpdReq.getCompanyId())
.fenceGroupId(vehicleUpdReq.getFenceGroupId()) .fenceGroupId(vehicleUpdReq.getFenceGroupId())
.warnStrategyId(vehicleUpdReq.getWarnStrategyId())
.build(); .build();
} }

View File

@ -3,9 +3,6 @@ package com.muyu.domain;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.muyu.common.core.annotation.Excel;
import com.muyu.common.core.annotation.Excel.ColumnType;
import com.muyu.common.core.web.domain.BaseEntity; import com.muyu.common.core.web.domain.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*; import lombok.*;
@ -44,7 +41,16 @@ public class VehicleType extends BaseEntity {
* *
*/ */
@Schema(type = "Integer",description = "报文模版外键") @Schema(type = "Integer",description = "报文模版外键")
private Integer messageTemplateId; private Long messageTemplateId;
/**
*
*/
public static VehicleType addBuilder(VehicleType vehicleType) {
return VehicleType.builder().
vehicleTypeId(vehicleType.getVehicleTypeId()).
vehicleTypeName(vehicleType.getVehicleTypeName()).
build();
}
} }

View File

@ -75,6 +75,14 @@ public class WarnRule extends BaseEntity{
@Excel(name = "最小值") @Excel(name = "最小值")
private Integer minValue; private Integer minValue;
/**
* id
*/
@Schema(type = "Integer",description = "策略外键id")
@Excel(name = "策略外键id")
private Integer warnStrategyId;
public static WarnRule updateBuilder(WarnRule warnRule, Supplier<Long> supplier) { public static WarnRule updateBuilder(WarnRule warnRule, Supplier<Long> supplier) {
return WarnRule.builder() return WarnRule.builder()
.warnRuleId(supplier.get()) .warnRuleId(supplier.get())

View File

@ -51,6 +51,7 @@ public class WarnStrategy extends BaseEntity{
private Long vehicleTypeId; private Long vehicleTypeId;
public static WarnStrategy updateBuilder(WarnStrategy warnStrategy, Supplier<Long> supplier) { public static WarnStrategy updateBuilder(WarnStrategy warnStrategy, Supplier<Long> supplier) {
return WarnStrategy.builder() return WarnStrategy.builder()
.warnStrategyId(supplier.get()) .warnStrategyId(supplier.get())

View File

@ -0,0 +1,30 @@
package com.muyu.domain.req;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
*
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Tag(name = "绑定围栏组参数")
public class BoundFenceGroupReq {
/**
* Id
*/
private Long vehicleId;
/**
* Ids
*/
private Long[] fenceGroupIds;
}

View File

@ -1,55 +0,0 @@
//package com.muyu.domain.req;
//
//import com.baomidou.mybatisplus.annotation.IdType;
//import com.baomidou.mybatisplus.annotation.TableId;
//import com.muyu.domain.Fence;
//import io.swagger.v3.oas.annotations.media.Schema;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import lombok.AllArgsConstructor;
//import lombok.Builder;
//import lombok.Data;
//import lombok.NoArgsConstructor;
//
//import java.util.List;
//
//@Data
//@Builder
//@AllArgsConstructor
//@NoArgsConstructor
//@Tag(name = "查看绑定的围栏信息")
//public class HaveFence {
//
// /**
// * 主键
// */
// @Schema(type = "Long",description = "主键")
// @TableId(value = "id",type = IdType.AUTO)
// private Long id;
//
// /**
// * 围栏名称
// */
// @Schema(type = "String",description = "围栏名称")
// private String fenceName;
//
// /**
// * 坐标
// */
// @Schema(type = "String",description = "坐标")
// private String coordinates;
//
// /**
// * 描述
// */
// @Schema(type = "String",description = "描述")
// private String description;
//
// /**
// * 电子围栏列表
// */
// @Schema(type = "List<Fence>",description = "电子围栏列表")
// List<Fence> fenceList;
//
//
//
//}

View File

@ -1,5 +1,7 @@
package com.muyu.domain.req; package com.muyu.domain.req;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.muyu.common.core.annotation.Excel; import com.muyu.common.core.annotation.Excel;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
@ -94,4 +96,9 @@ public class VehicleAddReq {
*/ */
@Schema(title = "电子围栏外键", type = "Integer", defaultValue = "1", description = "电子围栏外键") @Schema(title = "电子围栏外键", type = "Integer", defaultValue = "1", description = "电子围栏外键")
private Integer fenceGroupId; private Integer fenceGroupId;
/** 策略id */
@Schema(type = "Long",description = "策略id")
@TableId( type = IdType.AUTO)
private Long warnStrategyId;
} }

View File

@ -1,5 +1,7 @@
package com.muyu.domain.req; package com.muyu.domain.req;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.muyu.common.core.annotation.Excel; import com.muyu.common.core.annotation.Excel;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
@ -94,4 +96,11 @@ public class VehicleUpdReq {
*/ */
@Schema(title = "电子围栏外键", type = "Integer", defaultValue = "1", description = "电子围栏外键") @Schema(title = "电子围栏外键", type = "Integer", defaultValue = "1", description = "电子围栏外键")
private Integer fenceGroupId; private Integer fenceGroupId;
/** 策略id */
@Schema(type = "Long",description = "策略id")
@TableId( type = IdType.AUTO)
private Long warnStrategyId;
} }

View File

@ -23,4 +23,7 @@ public class WarnVehicleReq {
@Excel(name = "策略名称") @Excel(name = "策略名称")
private String strategyName; private String strategyName;
} }

View File

@ -53,6 +53,12 @@ public class MessageValueListResp {
@Schema(type = "Integer",title = "起始下标") @Schema(type = "Integer",title = "起始下标")
private Integer messageStartIndex; private Integer messageStartIndex;
/**
*
*/
@Schema(type = "Long",description = "报文模版主键")
private Long messageTemplateId;
/** /**
* *
*/ */

View File

@ -0,0 +1,56 @@
package com.muyu.domain.resp;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.muyu.common.core.annotation.Excel;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Tag(name = "WarnStrategyAndVin缓存预警信息获取vin")
public class WarnStrategyAndVinResp {
/**
* VIN
*/
@Schema(type = "String",description = "车辆VIN")
@Excel(name = "车辆VIN")
private String vehicleVin;
/**
* id
*/
@Schema(type = "Long",description = "策略id")
@TableId( type = IdType.AUTO)
private Long warnStrategyId;
/**
*
*/
@Schema(type = "String",description = "策略名称")
@Excel(name = "策略名称")
private String strategyName;
/**
* id
*/
@Schema(type = "Integer",description = "报文模版id")
@Excel(name = "报文模版id")
private Integer messageTemplateId;
/**
* id
*/
@Schema(type = "Long",description = "车辆类型id")
@Excel(name = "车辆类型id")
private Long vehicleTypeId;
}

View File

@ -66,4 +66,13 @@ public class WarnVehicleResp {
@Schema(type = "String",description = "报文模版名称") @Schema(type = "String",description = "报文模版名称")
private String messageTemplateName; private String messageTemplateName;
/**
* id
*/
@Schema(type = "Integer",description = "报文模版id")
@Excel(name = "报文模版id")
private Integer messageTemplateId;
} }

View File

@ -3,6 +3,7 @@ package com.muyu.enterprise.controller;
import com.muyu.common.redis.service.RedisService; import com.muyu.common.redis.service.RedisService;
import com.muyu.common.security.utils.SecurityUtils; import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser; import com.muyu.common.system.domain.LoginUser;
import com.muyu.enterprise.cache.AllFenceCahceService;
import com.muyu.enterprise.cache.FenceCahceService; import com.muyu.enterprise.cache.FenceCahceService;
import com.muyu.enterprise.cache.VehicleCacheService; import com.muyu.enterprise.cache.VehicleCacheService;
import com.muyu.enterprise.service.ElectService; import com.muyu.enterprise.service.ElectService;
@ -28,7 +29,9 @@ import java.security.Security;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/**
*
*/
@RequestMapping("/elect") @RequestMapping("/elect")
@RestController @RestController
@Log4j2 @Log4j2
@ -43,6 +46,8 @@ public class ElectController extends BaseController {
@Autowired @Autowired
private FenceCahceService fenceCahceService; private FenceCahceService fenceCahceService;
@Autowired
private AllFenceCahceService allFenceCahceService;
/** /**
@ -54,7 +59,10 @@ public class ElectController extends BaseController {
public Result<TableDataInfo<FenceResp>> showList(@RequestBody @Validated FenceReq req) { public Result<TableDataInfo<FenceResp>> showList(@RequestBody @Validated FenceReq req) {
startPage(); startPage();
List<FenceResp> list = electService.selectFenceList(req); List<FenceResp> list = electService.selectFenceList(req);
fenceCahceService.get(String.valueOf(req)); //将列表存到Redis
for (FenceResp fenceResp : list) {
allFenceCahceService.put(fenceResp.getCoordinates(),fenceResp);
}
return getDataTable(list); return getDataTable(list);
} }
@ -140,7 +148,7 @@ public class ElectController extends BaseController {
@DeleteMapping("/delMoreFence") @DeleteMapping("/delMoreFence")
@Operation(description = "批量删除电子围栏") @Operation(description = "批量删除电子围栏")
public Result delMore(@RequestBody List<Long> fenceIds){ public Result delMore(@RequestBody List<Long> fenceIds){
// electService.delMoreFence(fenceIds); //批量删除内容存到Redis
electService.removeBatchByIds(fenceIds); electService.removeBatchByIds(fenceIds);
return Result.success(null,"操作成功"); return Result.success(null,"操作成功");
} }
@ -155,5 +163,4 @@ public class ElectController extends BaseController {
return Result.success(fences); return Result.success(fences);
} }
} }

View File

@ -1,8 +1,11 @@
package com.muyu.enterprise.controller; package com.muyu.enterprise.controller;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.MessageTemplate; import com.muyu.domain.MessageTemplate;
import com.muyu.domain.req.MessageTemplateAddReq; import com.muyu.domain.req.MessageTemplateAddReq;
import com.muyu.domain.resp.MessageTemplateListResp; import com.muyu.domain.resp.MessageTemplateListResp;
import com.muyu.enterprise.cache.MessageTemplateCacheService;
import com.muyu.enterprise.service.MessageTemplateService; import com.muyu.enterprise.service.MessageTemplateService;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@ -30,6 +33,11 @@ public class MessageTemplateController {
@Autowired @Autowired
private MessageTemplateService messageTemplateService; private MessageTemplateService messageTemplateService;
//缓存
@Autowired
private MessageTemplateCacheService templateCacheService;
/** /**
* *
*1 *1
@ -55,8 +63,14 @@ public class MessageTemplateController {
*/ */
@PostMapping("/") @PostMapping("/")
public Result<String> save(@RequestBody MessageTemplateAddReq messageTemplateAddReq) { public Result<String> save(@RequestBody MessageTemplateAddReq messageTemplateAddReq) {
messageTemplateService.save(MessageTemplate.addBuild(messageTemplateAddReq)); boolean save = messageTemplateService.save(MessageTemplate.addBuild(messageTemplateAddReq));
return Result.success("添加成功"); //获取用户信息
LoginUser loginUser = SecurityUtils.getLoginUser();
//获取租户唯一标识
String databaseName = loginUser.getSysUser().getDatabaseName();
//添加到缓存
templateCacheService.put(databaseName+messageTemplateAddReq.getMessageTemplateName(), MessageTemplate.addBuild(messageTemplateAddReq));
return Result.success(save? "新增成功" : "新增失败");
} }
/** /**

View File

@ -1,5 +1,6 @@
package com.muyu.enterprise.controller; package com.muyu.enterprise.controller;
import com.muyu.enterprise.cache.AllMessageValueCacheService;
import com.muyu.enterprise.service.MessageValueService; import com.muyu.enterprise.service.MessageValueService;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import com.muyu.domain.MessageValue; import com.muyu.domain.MessageValue;
@ -32,6 +33,11 @@ public class MessageValueController {
@Autowired @Autowired
private MessageValueService messageValueService; private MessageValueService messageValueService;
//存Redis
@Autowired
private AllMessageValueCacheService allMessageValueCacheService;
/** /**
* *
* *
@ -42,6 +48,9 @@ public class MessageValueController {
@Operation(summary = "报文数据列表", description = "根据报文类别, 报文模版筛选报文数据") @Operation(summary = "报文数据列表", description = "根据报文类别, 报文模版筛选报文数据")
public Result<List<MessageValueListResp>> findAll(@RequestBody MessageValueReq messageValueReq) { public Result<List<MessageValueListResp>> findAll(@RequestBody MessageValueReq messageValueReq) {
List<MessageValueListResp> list = messageValueService.findAll(messageValueReq); List<MessageValueListResp> list = messageValueService.findAll(messageValueReq);
// for (MessageValueListResp messageValueListResp : list) {
// allMessageValueCacheService.put(String.valueOf(messageValueListResp.getMessageTemplateId()), (List<MessageValueListResp>) messageValueListResp);
// }
return Result.success(list); return Result.success(list);
} }
@ -93,6 +102,7 @@ public class MessageValueController {
@Operation(summary = "根据报文模版id查询报文数据", description = "根据报文模版id查询报文数据") @Operation(summary = "根据报文模版id查询报文数据", description = "根据报文模版id查询报文数据")
public Result<List<MessageValueListResp>> findByTemplateId(@PathVariable("templateId") Long templateId) { public Result<List<MessageValueListResp>> findByTemplateId(@PathVariable("templateId") Long templateId) {
List<MessageValueListResp> list = messageValueService.findByTemplateId(templateId); List<MessageValueListResp> list = messageValueService.findByTemplateId(templateId);
allMessageValueCacheService.put(String.valueOf(templateId), list);
return Result.success(list); return Result.success(list);
} }

View File

@ -2,6 +2,8 @@ package com.muyu.enterprise.controller;
import com.muyu.common.security.utils.SecurityUtils; import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser; import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.req.BoundFenceGroupReq;
import com.muyu.enterprise.cache.AllVehicleCacheService;
import com.muyu.enterprise.cache.VehicleCacheService; import com.muyu.enterprise.cache.VehicleCacheService;
import com.muyu.enterprise.service.VehicleService; import com.muyu.enterprise.service.VehicleService;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
@ -19,9 +21,11 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List; import java.util.List;
/** /**
@ -41,9 +45,12 @@ public class VehicleController extends BaseController {
@Autowired @Autowired
private VehicleService vehicleService; private VehicleService vehicleService;
//车辆缓存 //添加车辆缓存
@Autowired @Autowired
private VehicleCacheService vehicleCacheService; private VehicleCacheService vehicleCacheService;
//车辆信息
@Autowired
private AllVehicleCacheService allVehicleCacheService;
/** /**
@ -56,6 +63,14 @@ public class VehicleController extends BaseController {
public Result<TableDataInfo<VehicleManageResp>> getVehicleList(@RequestBody VehicleManageReq vehicleManageReq) { public Result<TableDataInfo<VehicleManageResp>> getVehicleList(@RequestBody VehicleManageReq vehicleManageReq) {
startPage(); startPage();
List<VehicleManageResp> list = vehicleService.getVehicleList(vehicleManageReq); List<VehicleManageResp> list = vehicleService.getVehicleList(vehicleManageReq);
// 将车辆信息存到Redis
// for (VehicleManageResp resp : list) {
// allVehicleCacheService.put(resp.getVehicleVin(), resp);
// }
List<Vehicle> vehicleList = vehicleService.list();
vehicleList.forEach(vehicle -> {
vehicleCacheService.put(vehicle.getVehicleVin(), vehicle);
});
return getDataTable(list); return getDataTable(list);
} }
@ -142,11 +157,12 @@ public class VehicleController extends BaseController {
/** /**
* *
*/ */
@GetMapping("/addBoundFenceGroup") @PostMapping("/addBoundFenceGroup")
@Operation(description = "车辆绑定围栏组") @Operation(description = "车辆绑定围栏组")
public Result<String> boundFenceGroup( public Result boundFenceGroup(
@Validated @RequestBody BoundMiddle boundMiddle){ @Validated @RequestBody BoundFenceGroupReq boundFenceGroupReq){
return null; vehicleService.boundFenceGroup(boundFenceGroupReq);
return Result.success("绑定成功");
} }
/** /**
@ -160,4 +176,5 @@ public class VehicleController extends BaseController {
Long templateId = vehicleService.findByVehicleVin(vehicleVin); Long templateId = vehicleService.findByVehicleVin(vehicleVin);
return Result.success(templateId); return Result.success(templateId);
} }
} }

View File

@ -1,15 +1,21 @@
package com.muyu.enterprise.controller; package com.muyu.enterprise.controller;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.MessageValue;
import com.muyu.domain.VehicleType; import com.muyu.domain.VehicleType;
import com.muyu.domain.req.MessageValueAddReq;
import com.muyu.domain.req.VehicleAddReq;
import com.muyu.enterprise.cache.AllVehicleTypeCacheService;
import com.muyu.enterprise.cache.VehicleCacheService;
import com.muyu.enterprise.cache.VehicleTypeCacheService;
import com.muyu.enterprise.service.VehicleTypeService; import com.muyu.enterprise.service.VehicleTypeService;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
@ -30,13 +36,47 @@ public class VehicleTypeController {
@Autowired @Autowired
private VehicleTypeService vehicleTypeService; private VehicleTypeService vehicleTypeService;
@Autowired
private VehicleTypeCacheService vehicleTypeCacheService;
//存缓存
@Autowired
private AllVehicleTypeCacheService allVehicleTypeCacheService;
/** /**
* *
* @return * @return
*/ */
@RequestMapping(path = "/", method = RequestMethod.POST) @RequestMapping(path = "/findAll", method = RequestMethod.POST)
@Operation(summary = "车辆类型列表",description = "车辆类型列表") @Operation(summary = "车辆类型列表",description = "车辆类型列表")
public Result<List<VehicleType>> findAll(){ public Result<List<VehicleType>> findAll(){
return Result.success(vehicleTypeService.list()); List<VehicleType> list = vehicleTypeService.list();
// for (VehicleType vehicleType : list) {
// allVehicleTypeCacheService.put(String.valueOf(vehicleType.getVehicleTypeId()),vehicleType);
// }
list.forEach(vehicleType -> {
vehicleTypeCacheService.put(String.valueOf(vehicleType.getVehicleTypeId()), vehicleType);
});
return Result.success(list);
}
/**
*
* @param vehicleType
* @return
*/
@PostMapping("/add")
@Operation(summary = "添加报文数据", description = "新增报文数据")
public Result<String> save(@RequestBody VehicleType vehicleType) {
boolean save = vehicleTypeService.save(vehicleType);
// //获取用户信息
// LoginUser loginUser = SecurityUtils.getLoginUser();
// //获取租户唯一标识
// String databaseName = loginUser.getSysUser().getDatabaseName();
//存到redis
// vehicleTypeCacheService.put(databaseName+vehicleType.getVehicleTypeId(),vehicleType);
vehicleTypeCacheService.put(String.valueOf(vehicleType.getVehicleTypeId()),vehicleType);
return Result.success(save? "添加成功" : "添加失败");
} }
} }

View File

@ -4,6 +4,7 @@ import com.muyu.common.core.domain.Result;
import com.muyu.common.security.utils.SecurityUtils; import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser; import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.WarnRule; import com.muyu.domain.WarnRule;
import com.muyu.enterprise.cache.AllWarnRuleCacheService;
import com.muyu.enterprise.cache.WarnRuleCacheService; import com.muyu.enterprise.cache.WarnRuleCacheService;
import com.muyu.enterprise.service.WarnRuleService; import com.muyu.enterprise.service.WarnRuleService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@ -22,6 +23,10 @@ public class WarnRuleController {
@Autowired @Autowired
private WarnRuleCacheService warnRuleCacheService; private WarnRuleCacheService warnRuleCacheService;
//存列表
@Autowired
private AllWarnRuleCacheService allWarnRuleCacheServicel;
/** /**
* *
* @return * @return
@ -29,7 +34,11 @@ public class WarnRuleController {
@RequestMapping(path = "/ruleList",method = RequestMethod.POST) @RequestMapping(path = "/ruleList",method = RequestMethod.POST)
@Operation(summary = "规则列表", description = "获取所有规则列表") @Operation(summary = "规则列表", description = "获取所有规则列表")
public Result<List<WarnRule>> ruleList(){ public Result<List<WarnRule>> ruleList(){
return Result.success(warnRuleService.list()); List<WarnRule> list = warnRuleService.list();
for (WarnRule warnRule : list) {
allWarnRuleCacheServicel.put(warnRule.getRuleName(),warnRule);
}
return Result.success(list);
} }
/** /**

View File

@ -4,6 +4,9 @@ import com.muyu.common.core.domain.Result;
import com.muyu.common.security.utils.SecurityUtils; import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser; import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.WarnStrategy; import com.muyu.domain.WarnStrategy;
import com.muyu.domain.resp.WarnStrategyAndVinResp;
import com.muyu.enterprise.cache.AllWarnStrategyAndVinCacheService;
import com.muyu.enterprise.cache.AllWarnStrategyCacheService;
import com.muyu.enterprise.cache.WarnStrategyCacheService; import com.muyu.enterprise.cache.WarnStrategyCacheService;
import com.muyu.enterprise.service.WarnStrategyService; import com.muyu.enterprise.service.WarnStrategyService;
import com.muyu.domain.req.WarnVehicleReq; import com.muyu.domain.req.WarnVehicleReq;
@ -26,14 +29,28 @@ public class WarnStrategyController {
@Autowired @Autowired
private WarnStrategyCacheService warnStrategyCacheService; private WarnStrategyCacheService warnStrategyCacheService;
//列表
@Autowired
private AllWarnStrategyCacheService allWarnStrategyCacheService;
//缓存策略和vin
@Autowired
private AllWarnStrategyAndVinCacheService allWarnStrategyAndVinCacheService;
/** /**
* *
* @return * @return
*/ */
@RequestMapping(path = "/strategyList",method = RequestMethod.POST) @RequestMapping(path = "/strategyList",method = RequestMethod.POST)
@Operation(summary = "策略列表", description = "获取所有策略列表") @Operation(summary = "策略列表", description = "获取所有策略列表")
public Result<List<WarnStrategy>> strategyList() { public Result<List<WarnVehicleResp>> strategyList(@RequestBody @Validated WarnVehicleReq req) {
return Result.success(warnStrategyService.list()); List<WarnVehicleResp> list = warnStrategyService.selectList(req);
// for (WarnVehicleResp warnVehicleResp : list) {
// //存进Redis
// allWarnStrategyCacheService.put(String.valueOf(warnVehicleResp.getVehicleVin()), warnVehicleResp);
// }
return Result.success(list);
} }
/** /**
@ -52,11 +69,11 @@ public class WarnStrategyController {
* @param warnVehicleReq * @param warnVehicleReq
* @return * @return
*/ */
@RequestMapping(path = "ruleStrategyList",method = RequestMethod.POST) // @RequestMapping(path = "ruleStrategyList",method = RequestMethod.POST)
@Operation(summary = "策略规则双表联查", description = "获取所有策略规则双表联查") // @Operation(summary = "策略规则双表联查", description = "获取所有策略规则双表联查")
public Result<List<WarnVehicleResp>> ruleStrategyList(@RequestBody WarnVehicleReq warnVehicleReq){ // public Result<List<WarnVehicleResp>> ruleStrategyList(@RequestBody WarnVehicleReq warnVehicleReq){
return Result.success(warnStrategyService.ruleStrategyList(warnVehicleReq)); // return Result.success(warnStrategyService.ruleStrategyList(warnVehicleReq));
} // }
/** /**
* *
@ -99,4 +116,18 @@ public class WarnStrategyController {
public Result strategyDelete(@PathVariable("id") Long id){ public Result strategyDelete(@PathVariable("id") Long id){
return Result.success(warnStrategyService.removeById(id)); return Result.success(warnStrategyService.removeById(id));
} }
/**
* vin
*/
@RequestMapping(path = "/vinStrategyList/{vehicleId}",method = RequestMethod.POST)
@Operation(summary = "通过vin缓存策略信息", description = "通过vin缓存策略信息")
public Result<List<WarnStrategyAndVinResp>> vinStrategyList(@PathVariable("vehicleId") Long vehicleId) {
List<WarnStrategyAndVinResp> warnStrategyAndVinResp = warnStrategyService.findById(vehicleId);
for (WarnStrategyAndVinResp strategyAndVinResp : warnStrategyAndVinResp) {
allWarnStrategyAndVinCacheService.put(strategyAndVinResp.getVehicleVin(), warnStrategyAndVinResp);
}
return Result.success(warnStrategyAndVinResp);
}
} }

View File

@ -30,11 +30,6 @@ public interface ElectMapper extends MPJBaseMapper<Fence> {
@Select("select * from fence where fence_id=#{fenceId}") @Select("select * from fence where fence_id=#{fenceId}")
List<Fence> mapShow(@Param("fenceId") Long fenceId); List<Fence> mapShow(@Param("fenceId") Long fenceId);
// /**
// * 根据id查询车辆
// */
// Fence boundFence(@Param("fenceId") Long fenceId);
/** /**
* () * ()
*/ */

View File

@ -28,7 +28,16 @@ public interface FencegroupMapper extends MPJBaseMapper<FenceGroup> {
@Select("SELECT g.fence_group_id,g.group_type,g.priority,g.`status`,f.fence_id, group_CONCAT( f.fence_name ) AS fence_name FROM fence_group g LEFT JOIN middle m ON m.fence_group_id = g.fence_group_id LEFT JOIN fence f ON m.fence_id = f.fence_id GROUP BY g.fence_group_id") @Select("SELECT g.fence_group_id,g.group_type,g.priority,g.`status`,f.fence_id, group_CONCAT( f.fence_name ) AS fence_name FROM fence_group g LEFT JOIN middle m ON m.fence_group_id = g.fence_group_id LEFT JOIN fence f ON m.fence_id = f.fence_id GROUP BY g.fence_group_id")
List<FenceGroup> showGroupList(FenceGroupReq req); List<FenceGroup> showGroupList(FenceGroupReq req);
@Insert("INSERT INTO `vehicle-basic`.`middle` (`fence_id`, `fence_group_id`) VALUES <foreach collection=\"fenceIds\" item=\"id\" separator=\",\"> (#{id},#{fenceGroupId}) </foreach>") // @Insert("INSERT INTO `vehicle-basic`.`middle` (`fence_id`, `fence_group_id`) VALUES <foreach collection='fenceIds' item='id' separator=','> (#{id},#{fenceGroupId}) </foreach>")
// @Insert({ "<script>", "INSERT INTO user_role (user_id, role_id) VALUES ", "<foreach collection='roleIds' item='roleId' separator=','>", "(#{userId}, #{roleId})", "</foreach>", "</script>" })
@Insert({
"<script>",
"INSERT INTO `vehicle-basic`.`middle` (fence_id, fence_group_id) VALUES ",
"<foreach collection='fenceIds' item='id' separator=','>",
"(#{id}, #{fenceGroupId})",
"</foreach>",
"</script>"
})
void addMiddle(@Param("fenceIds") Integer[] fenceIds,@Param("fenceGroupId") Long fenceGroupId); void addMiddle(@Param("fenceIds") Integer[] fenceIds,@Param("fenceGroupId") Long fenceGroupId);
} }

View File

@ -1,9 +1,12 @@
package com.muyu.enterprise.mapper; package com.muyu.enterprise.mapper;
import com.github.yulichang.base.MPJBaseMapper; import com.github.yulichang.base.MPJBaseMapper;
import com.muyu.domain.FenceGroup;
import com.muyu.domain.Vehicle; import com.muyu.domain.Vehicle;
import com.muyu.domain.req.BoundFenceGroupReq;
import com.muyu.domain.req.VehicleManageReq; import com.muyu.domain.req.VehicleManageReq;
import com.muyu.domain.resp.VehicleManageResp; import com.muyu.domain.resp.VehicleManageResp;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
@ -28,11 +31,6 @@ public interface VehicleMapper extends MPJBaseMapper<Vehicle> {
*/ */
List<VehicleManageResp> findAll(VehicleManageReq vehicleManageReq); List<VehicleManageResp> findAll(VehicleManageReq vehicleManageReq);
/**
*
*/
void bindFenceGroup(@Param("fenceGroupIds") Integer[] fenceGroupIds, @Param("vehicleId") Long vehicleId);
/** /**
* vinid * vinid
* @param vehicleVin * @param vehicleVin
@ -40,4 +38,20 @@ public interface VehicleMapper extends MPJBaseMapper<Vehicle> {
*/ */
@Select("SELECT t.message_template_id FROM vehicle v LEFT JOIN vehicle_type t ON v.vehicle_type_id = t.vehicle_type_id WHERE v.vehicle_vin = #{vehicleVin}") @Select("SELECT t.message_template_id FROM vehicle v LEFT JOIN vehicle_type t ON v.vehicle_type_id = t.vehicle_type_id WHERE v.vehicle_vin = #{vehicleVin}")
Long findByVehicleVin(String vehicleVin); Long findByVehicleVin(String vehicleVin);
/**
*
* @param boundFenceGroupReq
*/
// @Insert("INSERT INTO `vehicle-basic`.`bound_middle` (`fence_group_id`,`vehicle_id`) VALUES <foreach collection=\"fenceGroupIds\" item=\"id\" separator=\",\"> (#{id},#{vehicleId}) </foreach>")
@Insert({
"<script> INSERT INTO `vehicle-basic`.`bound_middle` (fence_group_id,vehicle_id) VALUES <foreach collection='fenceGroupIds' item='id' separator=','> (#{id}, #{vehicleId}) </foreach> </script>"
// "INSERT INTO `vehicle-basic`.`bound_middle` (fence_group_id, vehicle_id) VALUES <foreach collection=\"fenceGroupIds\" item=\"id\" separator=\",\"> (#{id}, #{vehicleId}) </foreach> "
})
void boundFenceGroup(BoundFenceGroupReq boundFenceGroupReq);
@Select("SELECT * FROM bound_middle bm LEFT JOIN vehicle v ON bm.vehicle_id=v.vehicle_id WHERE bm.fence_group_id = #{fenceGroupId}")
List<FenceGroup> showBoundFenceGroup(@Param("fenceGroupId") Long fenceGroupId);
} }

View File

@ -2,8 +2,18 @@ package com.muyu.enterprise.mapper;
import com.github.yulichang.base.MPJBaseMapper; import com.github.yulichang.base.MPJBaseMapper;
import com.muyu.domain.WarnStrategy; import com.muyu.domain.WarnStrategy;
import com.muyu.domain.resp.WarnStrategyAndVinResp;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper @Mapper
public interface WarnStrategyMapper extends MPJBaseMapper<WarnStrategy> { public interface WarnStrategyMapper extends MPJBaseMapper<WarnStrategy> {
@Select("SELECT vehicle.vehicle_vin, warn_strategy.warn_strategy_id, warn_strategy.vehicle_type_id, warn_strategy.message_template_id FROM vehicle LEFT JOIN warn_strategy ON vehicle.warn_strategy_id = warn_strategy.warn_strategy_id WHERE vehicle.vehicle_id = #{vehicleId}")
List<WarnStrategyAndVinResp> findById(Long vehicleId);
} }

View File

@ -30,11 +30,6 @@ public interface ElectService extends IService<Fence> {
*/ */
List<Fence> mapShow(@Param("fenceId") Long fenceId); List<Fence> mapShow(@Param("fenceId") Long fenceId);
// /**
// * 根据id查询车辆
// */
// Fence boundFence(@Param("fenceId") Long fenceId);
/** /**
* () * ()
*/ */

View File

@ -19,7 +19,5 @@ public interface IFencegroupService extends IService<FenceGroup> {
void addGroup(FenceGroupAddReq addReq); void addGroup(FenceGroupAddReq addReq);
// List<FenceGroup> haveFence(HaveFence haveFence);
//
} }

View File

@ -1,9 +1,12 @@
package com.muyu.enterprise.service; package com.muyu.enterprise.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.muyu.domain.FenceGroup;
import com.muyu.domain.Vehicle; import com.muyu.domain.Vehicle;
import com.muyu.domain.req.BoundFenceGroupReq;
import com.muyu.domain.req.VehicleManageReq; import com.muyu.domain.req.VehicleManageReq;
import com.muyu.domain.resp.VehicleManageResp; import com.muyu.domain.resp.VehicleManageResp;
import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
@ -31,4 +34,17 @@ public interface VehicleService extends IService<Vehicle> {
* @return * @return
*/ */
Long findByVehicleVin(String vehicleVin); Long findByVehicleVin(String vehicleVin);
/**
*
*/
void boundFenceGroup(BoundFenceGroupReq boundFenceGroupReq);
/**
*
* @param fenceGroupId
* @return
*/
List<FenceGroup> showBoundFenceGroup(@Param("fenceGroupId") Long fenceGroupId);
} }

View File

@ -3,11 +3,22 @@ package com.muyu.enterprise.service;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
import com.muyu.domain.WarnStrategy; import com.muyu.domain.WarnStrategy;
import com.muyu.domain.req.WarnVehicleReq; import com.muyu.domain.req.WarnVehicleReq;
import com.muyu.domain.resp.WarnStrategyAndVinResp;
import com.muyu.domain.resp.WarnVehicleResp; import com.muyu.domain.resp.WarnVehicleResp;
import java.util.List; import java.util.List;
public interface WarnStrategyService extends IService<WarnStrategy> { public interface WarnStrategyService extends IService<WarnStrategy> {
List<WarnVehicleResp>ruleStrategyList(WarnVehicleReq warnVehicleReq); // List<WarnVehicleResp>ruleStrategyList(WarnVehicleReq warnVehicleReq);
/**
*
*/
List<WarnVehicleResp> selectList(WarnVehicleReq req);
List<WarnStrategyAndVinResp> findById(Long vehicleId);
} }

View File

@ -2,6 +2,7 @@ package com.muyu.enterprise.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper; import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.muyu.enterprise.cache.FenceCahceService;
import com.muyu.enterprise.mapper.ElectMapper; import com.muyu.enterprise.mapper.ElectMapper;
import com.muyu.enterprise.mapper.WarnLogsMapper; import com.muyu.enterprise.mapper.WarnLogsMapper;
import com.muyu.enterprise.service.ElectService; import com.muyu.enterprise.service.ElectService;
@ -10,6 +11,7 @@ import com.muyu.domain.Fence;
import com.muyu.domain.LanType; import com.muyu.domain.LanType;
import com.muyu.domain.req.FenceReq; import com.muyu.domain.req.FenceReq;
import com.muyu.domain.resp.FenceResp; import com.muyu.domain.resp.FenceResp;
import com.muyu.enterprise.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -23,7 +25,12 @@ public class ElectServiceImpl
@Autowired @Autowired
private ElectMapper electMapper; private ElectMapper electMapper;
@Autowired @Autowired
private WarnLogsMapper warnLogsMapper; private VehicleService service;
@Autowired
private FenceCahceService fenceCahceService;
@Override @Override
public List<FenceResp> selectFenceList(FenceReq req) { public List<FenceResp> selectFenceList(FenceReq req) {
@ -39,15 +46,13 @@ public class ElectServiceImpl
req.getFenceName() req.getFenceName()
); );
List<FenceResp> list = electMapper.selectJoinList(FenceResp.class, wrapper); List<FenceResp> list = electMapper.selectJoinList(FenceResp.class, wrapper);
String decode = fenceCahceService.decode(String.valueOf(list));
//将获取到的数据存到Redis
// fenceCahceService.put(String.valueOf(decode),d);
return list; return list;
} }
//
// @Override
// public int addFence(Fence fence) {
// int i = electMapper.addFence(fence);
// return i;
// }
@Override @Override
public void updateFenceOn(Long fenceId) { public void updateFenceOn(Long fenceId) {
@ -65,11 +70,6 @@ public class ElectServiceImpl
return fences; return fences;
} }
// @Override
// public Fence boundFence(Long fenceId) {
// Fence fence = electMapper.boundFence(fenceId);
// return fence;
// }
@Override @Override
public List<Fence> showFenceBound(Long fenceGroupId) { public List<Fence> showFenceBound(Long fenceGroupId) {

View File

@ -41,10 +41,5 @@ public class FencegroupServiceImpl
} }
// @Override
// public List<FenceGroup> haveFence(HaveFence haveFence) {
// return null;
// }
} }

View File

@ -2,11 +2,12 @@ package com.muyu.enterprise.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.enterprise.mapper.MessageValueMapper;
import com.muyu.enterprise.service.MessageValueService;
import com.muyu.domain.MessageValue; import com.muyu.domain.MessageValue;
import com.muyu.domain.req.MessageValueReq; import com.muyu.domain.req.MessageValueReq;
import com.muyu.domain.resp.MessageValueListResp; import com.muyu.domain.resp.MessageValueListResp;
import com.muyu.enterprise.cache.AllMessageValueCacheService;
import com.muyu.enterprise.mapper.MessageValueMapper;
import com.muyu.enterprise.service.MessageValueService;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -31,6 +32,9 @@ public class MessageValueServiceImpl
@Autowired @Autowired
private MessageValueMapper messageValueMapper; private MessageValueMapper messageValueMapper;
@Autowired
private AllMessageValueCacheService allMessageValueCacheService;
public MessageValueServiceImpl(MessageValueMapper messageValueMapper) { public MessageValueServiceImpl(MessageValueMapper messageValueMapper) {
this.messageValueMapper = messageValueMapper; this.messageValueMapper = messageValueMapper;
} }
@ -63,51 +67,12 @@ public class MessageValueServiceImpl
LambdaQueryWrapper<MessageValue> queryWrapper = new LambdaQueryWrapper<>(); LambdaQueryWrapper<MessageValue> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MessageValue::getTemplateId, templateId); queryWrapper.eq(MessageValue::getTemplateId, templateId);
List<MessageValue> list = this.list(queryWrapper); List<MessageValue> list = this.list(queryWrapper);
return list.stream() List<MessageValueListResp> collect = list.stream()
.map(messageValue -> MessageValueListResp.valueBuild( .map(messageValue -> MessageValueListResp.valueBuild(
messageValue messageValue
) )
).collect(Collectors.toList()); ).collect(Collectors.toList());
// allMessageValueCacheService.put(String.valueOf(templateId), collect);
return collect;
} }
// @Override
// public JSONObject analysis(String testStr) {
//
// if (testStr.length() < 18){
// throw new RuntimeException("报文格式不正确");
// }
// //根据空格切割数据
// String[] hexArray = testStr.split(" ");
// StringBuilder result = new StringBuilder();
// for (String hex : hexArray) {
// int decimal = Integer.parseInt(hex, 16);
// result.append((char) decimal);
// }
// log.info(result);
// //取出车辆VIN码
// String vehicleVin = result.substring(1, 18);
// log.info("车辆VIN:" + vehicleVin);
// //根据车辆VIN码, 查找到报文模版id
// Long templateId = messageValueMapper.getTemplateId(vehicleVin);
// log.info("模版id:" + templateId);
// //获取到报文模版的列表
// List<MessageValueListResp> templateList = messageValueMapper.getTemplateList(templateId);
// //存储报文模板解析后数据
// JSONObject jsonObject = new JSONObject();
// for (MessageValueListResp messageValue : templateList) {
// //起始位下标
// Integer startIndex = messageValue.getMessageStartIndex() - 1;
// //截止位下标
// Integer endIndex = messageValue.getMessageEndIndex();
// //根据报文模版截取数据
// String value = result.substring(startIndex, endIndex);
// //存入数据
// jsonObject.put(messageValue.getMessageLabel(), value);
// }
// for (Map.Entry<String, Object> stringObjectEntry : jsonObject) {
// log.info(stringObjectEntry.getKey() + ":" + stringObjectEntry.getValue());
// }
// return jsonObject;
// }
} }

View File

@ -3,15 +3,19 @@ package com.muyu.enterprise.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper; import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.muyu.common.core.utils.StringUtils; import com.muyu.common.core.utils.StringUtils;
import com.muyu.domain.FenceGroup;
import com.muyu.domain.Vehicle; import com.muyu.domain.Vehicle;
import com.muyu.domain.VehicleType; import com.muyu.domain.VehicleType;
import com.muyu.domain.req.BoundFenceGroupReq;
import com.muyu.domain.req.VehicleManageReq; import com.muyu.domain.req.VehicleManageReq;
import com.muyu.domain.resp.VehicleManageResp; import com.muyu.domain.resp.VehicleManageResp;
import com.muyu.enterprise.cache.AllVehicleCacheService;
import com.muyu.enterprise.mapper.VehicleMapper; import com.muyu.enterprise.mapper.VehicleMapper;
import com.muyu.enterprise.service.VehicleService; import com.muyu.enterprise.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List; import java.util.List;
/** /**
@ -69,4 +73,16 @@ public class VehicleServiceImpl
return templateId; return templateId;
} }
@Override
public void boundFenceGroup(BoundFenceGroupReq boundFenceGroupReq) {
vehicleMapper.boundFenceGroup(boundFenceGroupReq);
}
@Override
public List<FenceGroup> showBoundFenceGroup(Long fenceGroupId) {
List<FenceGroup> fenceGroups = vehicleMapper.showBoundFenceGroup(fenceGroupId);
return fenceGroups;
}
} }

View File

@ -1,7 +1,10 @@
package com.muyu.enterprise.service.impl; package com.muyu.enterprise.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper; import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.muyu.domain.MessageTemplate;
import com.muyu.domain.resp.WarnStrategyAndVinResp;
import com.muyu.enterprise.mapper.WarnStrategyMapper; import com.muyu.enterprise.mapper.WarnStrategyMapper;
import com.muyu.enterprise.service.WarnStrategyService; import com.muyu.enterprise.service.WarnStrategyService;
import com.muyu.common.core.utils.StringUtils; import com.muyu.common.core.utils.StringUtils;
@ -12,6 +15,7 @@ import com.muyu.domain.resp.WarnVehicleResp;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List; import java.util.List;
@Service @Service
@ -21,17 +25,30 @@ public class WarnStrategyServiceImpl extends ServiceImpl<WarnStrategyMapper, War
@Autowired @Autowired
private WarnStrategyMapper warnStrategyMapper; private WarnStrategyMapper warnStrategyMapper;
@Override @Override
public List<WarnVehicleResp> ruleStrategyList(WarnVehicleReq warnVehicleReq) { public List<WarnVehicleResp> selectList(WarnVehicleReq req) {
MPJLambdaWrapper<WarnStrategy> wrapper = new MPJLambdaWrapper<>(); MPJLambdaWrapper<WarnStrategy> wrapper = new MPJLambdaWrapper<>();
wrapper.selectAll(WarnStrategy.class) wrapper.selectAll(WarnStrategy.class)
.selectAs(VehicleType::getVehicleTypeName,WarnVehicleResp::getVehicleTypeName) .selectAs(VehicleType::getVehicleTypeName,WarnVehicleResp::getVehicleTypeName)
.selectAs(MessageTemplate::getMessageTemplateName,WarnVehicleResp::getMessageTemplateName)
.leftJoin(VehicleType.class, VehicleType::getVehicleTypeId,WarnStrategy::getVehicleTypeId) .leftJoin(VehicleType.class, VehicleType::getVehicleTypeId,WarnStrategy::getVehicleTypeId)
.leftJoin(MessageTemplate.class, MessageTemplate::getMessageTemplateId,WarnStrategy::getMessageTemplateId)
.like( .like(
StringUtils.isNotEmpty(warnVehicleReq.getStrategyName()), StringUtils.isNotEmpty(req.getStrategyName()),
WarnStrategy::getStrategyName,warnVehicleReq.getStrategyName() WarnStrategy::getStrategyName,req.getStrategyName()
); );
List<WarnVehicleResp> list = warnStrategyMapper.selectJoinList(WarnVehicleResp.class, wrapper); List<WarnVehicleResp> list = warnStrategyMapper.selectJoinList(WarnVehicleResp.class, wrapper);
return list; return list;
} }
@Override
public List<WarnStrategyAndVinResp> findById(Long vehicleId) {
List<WarnStrategyAndVinResp> byId = warnStrategyMapper.findById(vehicleId);
if (byId == null) {
return null;
}
return byId;
}
} }

View File

@ -100,6 +100,25 @@
<artifactId>cloud-common-kafka</artifactId> <artifactId>cloud-common-kafka</artifactId>
</dependency> </dependency>
<!--缓存依赖-->
<dependency>
<groupId>com.muyu</groupId>
<artifactId>cloud-modules-enterprise-cache</artifactId>
<version>3.6.3</version>
</dependency>
<!-- MQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- 引入Caffeine缓存库-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.0.5</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -2,6 +2,7 @@ package com.muyu.processing.abstraction;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.muyu.processing.interfaces.EventInterface; import com.muyu.processing.interfaces.EventInterface;
import lombok.extern.log4j.Log4j2;
/** /**
* *
@ -11,6 +12,7 @@ import com.muyu.processing.interfaces.EventInterface;
* @nameEventProcessor * @nameEventProcessor
* @Date2024/9/28 20:58 * @Date2024/9/28 20:58
*/ */
@Log4j2
public abstract class EventProcessor implements EventInterface { public abstract class EventProcessor implements EventInterface {
private EventProcessor eventProcessor; private EventProcessor eventProcessor;

View File

@ -0,0 +1,24 @@
package com.muyu.processing.basic;
import cn.hutool.json.JSONObject;
import org.springframework.context.ApplicationEvent;
/**
*
* @Author
* @Packagecom.muyu.processing.basic
* @Projectcar-cloud-server
* @nameEventCustom
* @Date2024/9/29 21:18
*/
public class EventCustom extends ApplicationEvent{
private JSONObject data;
public EventCustom(Object source, JSONObject data) {
super(source);
this.data = data;
}
public JSONObject getData(){
return data;
}
}

View File

@ -0,0 +1,16 @@
package com.muyu.processing.basic;
import org.springframework.context.ApplicationListener;
/**
*
* @Author
* @Packagecom.muyu.processing.basic
* @Projectcar-cloud-server
* @nameEventListener
* @Date2024/9/29 22:29
*/
public interface EventListener extends ApplicationListener<EventCustom> {
void onEvent(EventCustom event);
}

View File

@ -0,0 +1,23 @@
package com.muyu.processing.basic;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
/**
*
* @Author
* @Packagecom.muyu.processing.basic
* @Projectcar-cloud-server
* @nameEventPublisher
* @Date2024/9/29 22:31
*/
public class EventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher){
this.publisher = applicationEventPublisher;
}
}

View File

@ -0,0 +1,23 @@
package com.muyu.processing.config;
import com.muyu.processing.listener.AddDatabaseListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
* @Author
* @Packagecom.muyu.processing.config
* @Projectcar-cloud-server
* @nameAppConfig
* @Date2024/9/29 22:23
*/
@Configuration
public class AppConfig {
@Bean
public AddDatabaseListener addDatabaseListener(){
return new AddDatabaseListener();
}
}

View File

@ -0,0 +1,42 @@
package com.muyu.processing.config;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
*
*/
@Component
public class ConfirmCallbackConfig implements RabbitTemplate.ConfirmCallback {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* bean
*/
@PostConstruct
public void init() {
this.rabbitTemplate.setConfirmCallback(this);
}
/**
*
* @param correlationData correlation data for the callback.
* @param ack true for ack, false for nack
* @param cause An optional cause, for nack, when available, otherwise null.
*/
@Override
public void confirm(CorrelationData correlationData, boolean ack, String cause) {
if (ack) {
System.out.println("消息发送到 broker 成功");
} else {
System.out.println("消息发送到 broker 失败,失败的原因:" + cause);
}
}
}

View File

@ -0,0 +1,107 @@
package com.muyu.processing.config;
import lombok.extern.log4j.Log4j2;
import org.apache.iotdb.isession.SessionDataSet;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.tsfile.read.common.Field;
import org.apache.iotdb.tsfile.read.common.RowRecord;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* iotdb
* @Author
* @Packagecom.muyu.processing.config
* @Projectcar-cloud-server
* @nameIotDBConfig
* @Date2024/9/30 15:13
*/
@Log4j2
@Component
@Configuration
public class IotDBConfig {
/**
* session
*/
@Bean
public static Session session(){
Session session = null;
try {
session = new Session(
"47.101.49.53",
6667,
"root",
"root"
);
session.open(false);
session.setFetchSize(100);
} catch (Exception e) {
throw new RuntimeException(e);
}
return session;
}
/**
*
*/
public void execute(String deviceId, Long time, List<String> measurement, List<String> values){
if (!CollectionUtils.isEmpty(measurement) && !CollectionUtils.isEmpty(values)){
try {
session().insertAlignedRecord(deviceId,time,measurement,values);
} catch (IoTDBConnectionException e) {
throw new RuntimeException(e);
} catch (StatementExecutionException e) {
throw new RuntimeException(e);
}
}
}
/**
*
*/
public List<HashMap<String, Object>> executeQuery(String sql){
log.info("sql:{}",sql);
ArrayList<HashMap<String, Object>> list = new ArrayList<>();
try {
SessionDataSet sessionDataSet = session().executeQueryStatement(sql);
int fetchSize = sessionDataSet.getFetchSize();
List<String> columnNames = sessionDataSet.getColumnNames();
List<String> columnTypes = sessionDataSet.getColumnTypes();
System.out.println(columnNames);
System.out.println(columnTypes);
if (fetchSize > 0){
while (sessionDataSet.hasNext()){
HashMap<String, Object> map = new HashMap<>();
RowRecord next = sessionDataSet.next();
List<Field> fields = next.getFields();
// 查询结果第一个为时间戳
long timestamp = next.getTimestamp();
for (int i = 0; i < fields.size(); i++) {
Field field = fields.get(i);
String key = field.getStringValue();
// 这里的需要按照类型获取
Object value = field.getObjectValue(field.getDataType());
map.put(key, value);
}
list.add(map);
}
}
sessionDataSet.closeOperationHandle();
} catch (Exception e) {
throw new RuntimeException(e);
}
return list;
}
}

View File

@ -0,0 +1,50 @@
package com.muyu.processing.config;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* RabbitAdmin
*/
@Configuration
public class RabbitAdminConfig {
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.username}")
private String username;
@Value("${spring.rabbitmq.password}")
private String password;
@Value("${spring.rabbitmq.virtual-host}")
private String virtualhost;
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses(host);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(virtualhost);
// 配置发送确认回调时次配置必须配置否则即使在RabbitTemplate配置了ConfirmCallback也不会生效
connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
connectionFactory.setPublisherReturns(true);
return connectionFactory;
}
/**
* rabbitAdmin
* @param connectionFactory
* @return
*/
@Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
rabbitAdmin.setAutoStartup(true);
return rabbitAdmin;
}
}

View File

@ -0,0 +1,18 @@
package com.muyu.processing.config;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
*/
@Configuration
public class RabbitmqConfig {
// 消息转换配置
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}
}

View File

@ -0,0 +1,39 @@
package com.muyu.processing.config;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
*
*/
@Component
public class ReturnsCallbackConfig implements RabbitTemplate.ReturnsCallback {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* bean
*/
@PostConstruct
public void init() {
this.rabbitTemplate.setReturnsCallback(this);
}
/**
* queue
*
* @param returnedMessage the returned message and metadata.
*/
@Override
public void returnedMessage(ReturnedMessage returnedMessage) {
System.out.println("消息" + returnedMessage.getMessage().toString() +
"被交换机" + returnedMessage.getExchange() + "回退!"
+ "退回原因为:" + returnedMessage.getReplyText());
// TODO 回退了所有的信息,可做补偿机制
}
}

View File

@ -6,7 +6,12 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists; import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.muyu.common.core.constant.KafkaConstants; import com.muyu.common.core.constant.KafkaConstants;
import com.muyu.domain.Fence;
import com.muyu.domain.Vehicle;
import com.muyu.domain.WarnRule;
import com.muyu.domain.WarnStrategy;
import com.muyu.processing.interfaces.EventInterface; import com.muyu.processing.interfaces.EventInterface;
import com.muyu.processing.utils.CacheUtil;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.ConsumerRecords;
@ -17,8 +22,10 @@ import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.Duration; import java.time.Duration;
import java.util.Collection; import java.util.Collection;
import java.util.Map;
/** /**
* kafka
* @Author * @Author
* @Packagecom.muyu.processing.consumer * @Packagecom.muyu.processing.consumer
* @Projectcar-cloud-server * @Projectcar-cloud-server
@ -32,6 +39,9 @@ public class KafkaConsumerService implements InitializingBean {
@Resource @Resource
private KafkaConsumer kafkaConsumer; private KafkaConsumer kafkaConsumer;
@Resource
private CacheUtil cacheUtil;
// @Resource // @Resource
// private EventInterface eventInterface; // private EventInterface eventInterface;
@ -53,8 +63,16 @@ public class KafkaConsumerService implements InitializingBean {
JSONObject jsonObject = JSON.parseObject(originalMsg); JSONObject jsonObject = JSON.parseObject(originalMsg);
log.info("消费数据转换为JSON对象: " + jsonObject); log.info("消费数据转换为JSON对象: " + jsonObject);
log.info("消费数据转换为JSON对象: " + jsonObject.toString()); log.info("消费数据转换为JSON对象: " + jsonObject.toString());
// eventInterface.handle(jsonObject);
String value = jsonObject.toString();
String vin = value.substring(0, 11);
Map<String, Object> map = (Map<String, Object>) cacheUtil.get(vin);
WarnRule warnRule = (WarnRule) map.get("warnRule");
WarnStrategy warnStrategy = (WarnStrategy) map.get("warnStrategy");
Vehicle vehicle = (Vehicle) map.get("vehicle");
Object breakdown = map.get("breakdown");
Fence fence = (Fence) map.get("fence");
// eventInterface.handle(jsonObject);
} }
} }
}); });

View File

@ -0,0 +1,45 @@
package com.muyu.processing.consumer;
import com.muyu.enterprise.cache.FaultCacheService;
import com.muyu.enterprise.cache.FenceCahceService;
import com.muyu.enterprise.cache.VehicleCacheService;
import com.muyu.enterprise.cache.WarnRuleCacheService;
import com.muyu.processing.utils.CacheUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* 线
* @Author
* @Packagecom.muyu.processing.consumer
* @Projectcloud-vehicle
* @nameOfflineMonitoringConsumer
* @Date2024/10/4 14:48
*/
@Log4j2
@Component
public class OfflineMonitoringConsumer {
@Resource
private CacheUtil cacheUtil;
/**
*
* @param vin vin
*/
@RabbitListener(queuesToDeclare = @Queue("offline_monitoring"))
public void receive(String vin){
log.info("清除缓存中的数据,车辆vin: {}", vin);
// 清除缓存
cacheUtil.remove(vin);
}
}

View File

@ -0,0 +1,81 @@
package com.muyu.processing.consumer;
import com.muyu.domain.Fence;
import com.muyu.domain.Vehicle;
import com.muyu.domain.WarnRule;
import com.muyu.domain.WarnStrategy;
import com.muyu.enterprise.cache.*;
import com.muyu.processing.utils.CacheUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
/**
* 线
* @Author
* @Packagecom.muyu.processing.consumer
* @Projectcar-cloud-server
* @nameMQconsumer
* @Date2024/9/29 17:19
*/
@Log4j2
@Component
public class OnLineMonitoringConsumer {
@Resource
private CacheUtil cacheUtil;
@Resource
private VehicleCacheService vehicleCacheService;
@Resource
private FaultCacheService faultCacheService;
@Resource
private FenceCahceService fenceCahceService;
@Resource
private WarnRuleCacheService warnRuleCacheService;
@Resource
private WarnStrategyCacheService warnStrategyCacheService;
/**
* 线线
*/
@RabbitListener(queuesToDeclare = @Queue("long_time_no_see"))
public void receive(String vin, Message message, Channel channel){
try {
log.info("添加本地缓存,车辆vin: {}", vin);
WarnRule warnRule = warnRuleCacheService.get(vin);
WarnStrategy warnStrategy = warnStrategyCacheService.get(vin);
Vehicle vehicle = vehicleCacheService.get(vin);
Object breakdown = faultCacheService.get(vin);
Fence fence = fenceCahceService.get(vin);
HashMap<String, Object> map = new HashMap<>();
map.put("warnRule",warnRule);
map.put("warnStrategy",warnStrategy);
map.put("vehicle",vehicle);
map.put("breakdown",breakdown);
map.put("fence",fence);
cacheUtil.put(vin,map);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
} catch (Exception e) {
try {
channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
}

View File

@ -0,0 +1,59 @@
package com.muyu.processing.controller;
import com.muyu.processing.config.IotDBConfig;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* iotdb
* @Author
* @Packagecom.muyu.processing.controller
* @Projectcar-cloud-server
* @nameIotdbController
* @Date2024/10/2 9:39
*/
@RestController
@RequestMapping("iotdb")
public class IotDbController {
@Resource
private IotDBConfig iotDBConfig;
private String json = "{\n" + " \"carVin\": \"VIN123456\",\n" +
" \"carName\": \"宝马\",\n" + "}";
/**
*
*/
@GetMapping("add")
public void add(){
// Map map = JSON.parseObject(json, Map.class);
// Set set = map.keySet();
ArrayList<String> key = new ArrayList<>();
ArrayList<String> value = new ArrayList<>();
key.add("car_vin");
key.add("car_name");
value.add("VIN123456");
value.add("宝马");
System.out.println(key);
System.out.println(value);
long l = System.currentTimeMillis();
iotDBConfig.execute("root.vehicle", l, key, value);
}
/**
*
*/
@GetMapping("findList")
public void findList(){
String sql = "select * from root.vehicle";
List<HashMap<String, Object>> list = iotDBConfig.executeQuery(sql);
System.out.println(list);
}
}

View File

@ -1,12 +1,14 @@
package com.muyu.processing.controller; package com.muyu.processing.controller;
import com.alibaba.fastjson.JSONObject; import cn.hutool.json.JSONObject;
import com.muyu.common.core.constant.KafkaConstants; import com.muyu.common.core.constant.KafkaConstants;
import com.muyu.common.core.utils.uuid.UUID;
import com.muyu.common.kafka.config.KafkaProducerConfig; import com.muyu.common.kafka.config.KafkaProducerConfig;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.protocol.types.Field; import org.apache.kafka.common.protocol.types.Field;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -14,6 +16,7 @@ import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource; import javax.annotation.Resource;
/** /**
* -
* @Author * @Author
* @Packagecom.muyu.processing.controller * @Packagecom.muyu.processing.controller
* @Projectcar-cloud-server * @Projectcar-cloud-server
@ -29,10 +32,44 @@ public class TestKafka {
@Resource @Resource
private KafkaProducer<String, String> kafkaProducer; private KafkaProducer<String, String> kafkaProducer;
@Resource
private RabbitTemplate rabbitTemplate;
/**
* Kafka
* @return String
*/
@GetMapping("/send") @GetMapping("/send")
public void sendMsg(){ public String sendMsg(){
ProducerRecord<String, String> producerRecord = new ProducerRecord<>("zeshi", "你好啊"); JSONObject entries = new JSONObject();
entries.set("vin","vin123468");
entries.set("name","宝马");
String entriesString = entries.toString();
ProducerRecord<String, String> producerRecord = new ProducerRecord<>("zeshi", entriesString);
kafkaProducer.send(producerRecord); kafkaProducer.send(producerRecord);
return "OK";
} }
/**
* MQ
* @return String
*/
@GetMapping("/sendMQ")
public String sendMQ(){
rabbitTemplate.convertAndSend("long_time_no_see","晨哀,好久不见",message -> {
message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
return message;
});
return "OK";
}
/**
* MQ
* @return String
*/
@GetMapping("/sendDui")
public String sedDui() {
rabbitTemplate.convertAndSend("myExchange","Im.fine","");
return "OK";
}
} }

View File

@ -1,6 +1,8 @@
package com.muyu.processing.interfaces; package com.muyu.processing.interfaces;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Component;
/** /**
* *

View File

@ -0,0 +1,34 @@
package com.muyu.processing.listener;
import cn.hutool.json.JSONObject;
import com.muyu.processing.basic.EventCustom;
import com.muyu.processing.basic.EventListener;
import java.util.ArrayList;
/**
*
* @Author
* @Packagecom.muyu.processing.listener
* @Projectcar-cloud-server
* @nameAddDatabaseListener
* @Date2024/9/29 22:25
*/
public class AddDatabaseListener implements EventListener {
@Override
public void onEvent(EventCustom event) {
JSONObject jsonObject = event.getData();
ArrayList<Object> keys = new ArrayList<>();
ArrayList<Object> values = new ArrayList<>();
jsonObject.forEach((key, value) ->{
keys.add(key);
values.add(value);
});
// 添加数据库
}
@Override
public void onApplicationEvent(EventCustom event) {
onEvent(event);
}
}

View File

@ -0,0 +1,58 @@
package com.muyu.processing.utils;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.stereotype.Component;
/**
*
* @Author
* @Packagecom.muyu.processing.utils
* @Projectcloud-vehicle
* @nameCacheUtil
* @Date2024/10/4 15:14
*/
@Component
public class CacheUtil<T> {
/**
*
*/
private final Cache<String, T> cache;
/**
*
*/
public CacheUtil(){
this.cache = Caffeine.newBuilder()
.maximumSize(500L)
.build();
}
/**
*
* @param key
* @return
*/
public T get(String key){
return cache.getIfPresent(key);
}
/**
*
* @param key
* @param value
*/
public void put(String key, T value){
cache.put(key, value);
}
/**
*
* @param key
*/
public void remove(String key){
cache.invalidate(key);
}
}

View File

@ -13,6 +13,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* IotDb
* @Author * @Author
* @Packagecom.muyu.processing.utils * @Packagecom.muyu.processing.utils
* @Projectcar-cloud-server * @Projectcar-cloud-server

View File

@ -7,7 +7,7 @@ nacos:
addr: 47.101.49.53:8848 addr: 47.101.49.53:8848
user-name: nacos user-name: nacos
password: nacos password: nacos
namespace: seven namespace: dev
# SPRING_AMQP_DESERIALIZATION_TRUST_ALL=true spring.amqp.deserialization.trust.all # SPRING_AMQP_DESERIALIZATION_TRUST_ALL=true spring.amqp.deserialization.trust.all
# Spring # Spring
spring: spring:

View File

@ -116,6 +116,12 @@
<artifactId>cloud-common-kafka</artifactId> <artifactId>cloud-common-kafka</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.muyu</groupId>
<artifactId>cloud-modules-enterprise-cache</artifactId>
<version>3.6.3</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -1,40 +0,0 @@
package com.muyu.cloud.protocol.parsing.feign;
import com.muyu.common.core.domain.Result;
import com.muyu.domain.resp.MessageValueListResp;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* @Author: LiDongJia
* @Package: com.muyu.cloud.protocol.parsing.feign
* @Project: 2112-car-cloud-server
* @name: RemoteServiceClient
* @Date: 2024/9/28 14:49
* @Description:
*/
@FeignClient(name = "cloud-car")
public interface RemoteServiceClient {
/**
* vinid
* @param vehicleVin
* @return
*/
@GetMapping("/vehicleManage/findByVehicleVin/{vehicleVin}")
@Operation(description = "通过车辆vin码查询模板id")
public Result<Long> findByVehicleVin(@PathVariable("vehicleVin") String vehicleVin);
/**
* id
* @param templateId
* @return
*/
@GetMapping("/messageValue/findByTemplateId/{templateId}")
@Operation(summary = "根据报文模版id查询报文数据", description = "根据报文模版id查询报文数据")
public Result<List<MessageValueListResp>> findByTemplateId(@PathVariable("templateId") Long templateId);
}

View File

@ -1,40 +0,0 @@
package com.muyu.cloud.protocol.parsing.feign.factory;
import com.muyu.cloud.protocol.parsing.feign.RemoteServiceClient;
import com.muyu.common.core.domain.Result;
import com.muyu.domain.resp.MessageValueListResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import java.util.List;
/**
*
* @Author
* @Packagecom.muyu.analysis.parsing.remote.factory
* @Projectcloud-server
* @nameRemoteServiceClientFactory
* @Date2024/9/28 21:16
*/
public class RemoteServiceClientFactory implements FallbackFactory<RemoteServiceClient>
{
private static final Logger log = LoggerFactory.getLogger(com.muyu.cloud.protocol.parsing.feign.factory.RemoteServiceClientFactory.class);
@Override
public RemoteServiceClient create(Throwable throwable) {
log.error("报文模版传参调用失败:{}", throwable.getMessage());
return new RemoteServiceClient() {
@Override
public Result<Long> findByVehicleVin(String vehicleVin) {
return Result.success(Long.valueOf(vehicleVin));
}
@Override
public Result<List<MessageValueListResp>> findByTemplateId(Long templateId) {
return null;
}
};
}
}

View File

@ -1,16 +1,17 @@
package com.muyu.cloud.protocol.parsing.test; package com.muyu.cloud.protocol.parsing.test;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON; import com.muyu.domain.Vehicle;
import com.muyu.cloud.protocol.parsing.feign.RemoteServiceClient; import com.muyu.domain.VehicleType;
import com.muyu.common.core.domain.Result;
import com.muyu.domain.resp.MessageValueListResp; import com.muyu.domain.resp.MessageValueListResp;
import com.muyu.enterprise.cache.AllMessageValueCacheService;
import com.muyu.enterprise.cache.VehicleCacheService;
import com.muyu.enterprise.cache.VehicleTypeCacheService;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.ProducerRecord;
import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@ -27,17 +28,20 @@ import java.util.List;
*/ */
@Log4j2 @Log4j2
@Component @Component
public class ParsingTest { public class ParsingMessage {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private RemoteServiceClient remoteServiceClient;
@Resource @Resource
private KafkaProducer<String, String> kafkaProducer; private KafkaProducer<String, String> kafkaProducer;
@Autowired
private VehicleCacheService vehicleCacheService;
@Autowired
private VehicleTypeCacheService vehicleTypeCacheService;
@Autowired
private AllMessageValueCacheService allMessageValueCacheService;
/** /**
* *
*/ */
@ -92,32 +96,34 @@ public class ParsingTest {
String vehicleVin = result.substring(1, 18); String vehicleVin = result.substring(1, 18);
log.info("车辆VIN码: " + vehicleVin); log.info("车辆VIN码: " + vehicleVin);
//根据车辆VIN码查询报文模板ID //根据车辆VIN码查询报文模板ID
Result<Long> byVehicleVin = remoteServiceClient.findByVehicleVin(vehicleVin); Vehicle vehicle = vehicleCacheService.get(vehicleVin);
Long templateId = byVehicleVin.getData(); Long vehicleTypeId = vehicle.getVehicleTypeId();
List<MessageValueListResp> templateList; VehicleType vehicleType = vehicleTypeCacheService.get(String.valueOf(vehicleTypeId));
//从redis缓存中获取报文模板数据 Long templateId = vehicleType.getMessageTemplateId();
try { List<MessageValueListResp> templateList = allMessageValueCacheService.get(String.valueOf(templateId));
String redisKey = "messageTemplate" + templateId; // //从redis缓存中获取报文模板数据
if (redisTemplate.hasKey(redisKey)) { // try {
List<Object> list = redisTemplate.opsForList().range(redisKey, 0, -1); // String redisKey = "messageTemplate" + templateId;
templateList = list.stream() // if (redisTemplate.hasKey(redisKey)) {
.map(obj -> JSON.parseObject(obj.toString(), MessageValueListResp.class)) // List<Object> list = redisTemplate.opsForList().range(redisKey, 0, -1);
.toList(); // templateList = list.stream()
log.info("Redis缓存查询成功"); // .map(obj -> JSON.parseObject(obj.toString(), MessageValueListResp.class))
} else { // .toList();
Result<List<MessageValueListResp>> byTemplateId = remoteServiceClient.findByTemplateId(templateId); // log.info("Redis缓存查询成功");
templateList = byTemplateId.getData(); // } else {
templateList.forEach( // Result<List<MessageValueListResp>> byTemplateId = remoteServiceClient.findByTemplateId(templateId);
listResp -> // templateList = byTemplateId.getData();
redisTemplate.opsForList().rightPush( // templateList.forEach(
redisKey, JSON.toJSONString(listResp) // listResp ->
) // redisTemplate.opsForList().rightPush(
); // redisKey, JSON.toJSONString(listResp)
log.info("数据库查询成功"); // )
} // );
} catch (Exception e) { // log.info("数据库查询成功");
throw new RuntimeException("获取报文模板失败"); // }
} // } catch (Exception e) {
// throw new RuntimeException("获取报文模板失败");
// }
//判断报文模板列表不为空 //判断报文模板列表不为空
if (templateList.isEmpty()) { if (templateList.isEmpty()) {
throw new RuntimeException("报文模版为空"); throw new RuntimeException("报文模版为空");

View File

@ -67,10 +67,10 @@
</dependency> </dependency>
<!-- MuYu Common Log --> <!-- MuYu Common Log -->
<dependency> <!-- <dependency>-->
<groupId>com.muyu</groupId> <!-- <groupId>com.muyu</groupId>-->
<artifactId>cloud-common-log</artifactId> <!-- <artifactId>cloud-common-log</artifactId>-->
</dependency> <!-- </dependency>-->
<!-- 接口模块 --> <!-- 接口模块 -->
<dependency> <dependency>
@ -83,6 +83,10 @@
<groupId>com.muyu</groupId> <groupId>com.muyu</groupId>
<artifactId>cloud-common-xxl</artifactId> <artifactId>cloud-common-xxl</artifactId>
</dependency> </dependency>
<!-- <dependency>-->
<!-- <groupId>com.muyu</groupId>-->
<!-- <artifactId>cloud-common-redis</artifactId>-->
<!-- </dependency>-->
<dependency> <dependency>
<groupId>com.muyu</groupId> <groupId>com.muyu</groupId>
@ -115,6 +119,11 @@
<artifactId>tea-util</artifactId> <artifactId>tea-util</artifactId>
<version>0.2.21</version> <version>0.2.21</version>
</dependency> </dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>darabonba-env</artifactId>
<version>0.1.1</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -4,13 +4,16 @@ import com.muyu.common.security.annotation.EnableCustomConfig;
import com.muyu.common.security.annotation.EnableMyFeignClients; import com.muyu.common.security.annotation.EnableMyFeignClients;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
/** /**
* *
*/ */
@EnableCustomConfig @EnableCustomConfig
@EnableMyFeignClients @EnableFeignClients
@SpringBootApplication @SpringBootApplication
//@ComponentScan(basePackages = "com.muyu")
public class VehicleGatewayApplication { public class VehicleGatewayApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(VehicleGatewayApplication.class, args); SpringApplication.run(VehicleGatewayApplication.class, args);

View File

@ -0,0 +1,36 @@
package com.muyu.cloud.vehicle.gateway.aliyun;
import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;
import com.muyu.cloud.vehicle.gateway.config.AliProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Ali
*/
@Configuration
public class AliYunConfig {
@Autowired
private AliProperties aliProperties;
@Bean
public Client createClient() {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
Config config = new Config()
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
.setAccessKeyId(aliProperties.getAccessKeyId())
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
.setAccessKeySecret(aliProperties.getAccessKeySecret());
// Endpoint 请参考 https://api.aliyun.com/product/Ecs
config.endpoint = aliProperties.getEndpoint();
try {
return new Client(config);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,30 @@
package com.muyu.cloud.vehicle.gateway.aliyun.ecs;
import com.muyu.cloud.vehicle.gateway.aliyun.service.AliYunEcsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
*
*/
@Log4j2
@Component
public class DeleteSample implements DisposableBean {
@Autowired
private AliYunEcsService aliYunEcsService;
@Override
public void destroy() {
try{
log.info("==========开始执行删除实例方法");
Thread.sleep(10000);
aliYunEcsService.deleteInstance();
} catch (Exception e) {
log.info("删除实例失败");
throw new RuntimeException(e);
}
log.info("删除实例成功");
}
}

View File

@ -0,0 +1,55 @@
package com.muyu.cloud.vehicle.gateway.aliyun.ecs;
import com.muyu.cloud.vehicle.gateway.aliyun.service.AliYunEcsService;
import com.muyu.cloud.vehicle.gateway.config.AliProperties;
import com.muyu.cloud.vehicle.gateway.domain.AliInstance;
import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
/**
*
*/
@Log4j2
@Component
public class Sample implements ApplicationRunner{
@Autowired
private AliYunEcsService aliYunEcsService;
@Autowired
private AliProperties aliProperties;
@Override
public void run(ApplicationArguments args) throws Exception {
List<String> list;
try{
log.info("开始创建实例");
list =aliYunEcsService.generateInstance(aliProperties.getAmount());
} catch (Exception e) {
log.info("创建实例失败");
throw new RuntimeException(e);
}
log.info("创建实例成功");
// redisService.setCacheList("instanceIds",list);
try{
Thread.sleep(9000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
List<AliInstance> aliInstances = aliYunEcsService.selectInstance(list);
log.info("查询实例信息成功:{}",aliInstances);
//将查询到的实例信息列表存储到redis中
// redisService.setCacheList("instanceList",aliInstances);
// log.info("redis存储成功{}",aliInstances);
}
}

View File

@ -0,0 +1,201 @@
package com.muyu.cloud.vehicle.gateway.aliyun.service;
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.muyu.cloud.vehicle.gateway.config.AliProperties;
import com.muyu.cloud.vehicle.gateway.domain.AliInstance;
import com.muyu.common.core.exception.ServiceException;
import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
*ali
*/
@Log4j2
@Service
public class AliYunEcsService {
/**
*
*/
@Autowired
private AliProperties aliProperties;
/**
*
*/
@Autowired
private Client client;
/**
* redis
*/
@Autowired
private RedisService redisService;
/**
*
*
* @param amount
* @return id
*/
public List<String> generateInstance(Integer amount) {
redisService.deleteObject("oneIpList");
redisService.deleteObject("oneCount");
redisService.deleteObject("oneVinIp");
// 检查生成实例的数量是否有效
if (amount == null || amount <= 0) {
throw new ServiceException("生成数量不能小于1");
}
// 初始化系统盘配置
RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk();
systemDisk.setSize("20");
systemDisk.setCategory("cloud_essd");
// 创建创建实例请求对象并设置参数
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
// 设置地域ID
.setRegionId(aliProperties.getRegionId())
// 设置镜像ID
.setImageId(aliProperties.getImageId())
// 设置实例规格类型
.setInstanceType(aliProperties.getInstanceType())
// 设置安全组ID
.setSecurityGroupId(aliProperties.getSecurityGroupId())
// 设置虚拟交换机ID
.setVSwitchId(aliProperties.getSwitchId())
// 设置实例名称
.setInstanceName("server-mqtt")
// 设置付费类型 按量付费
.setInstanceChargeType("PostPaid")
// 设置系统盘配置
.setSystemDisk(systemDisk)
// 设置用户名
.setHostName("root")
// 设置密码
.setPassword("@ywt0219")
// 设置要创建的实例数量
.setAmount(amount)
.setInternetChargeType("PayByTraffic")
.setInternetMaxBandwidthOut(1);
// 创建运行时选项对象
RuntimeOptions runtimeOptions = new RuntimeOptions();
// 尝试执行创建实例请求
try {
// 复制代码运行请自行打印 API 的返回值
RunInstancesResponse runInstancesResponse = client.runInstancesWithOptions(runInstancesRequest, runtimeOptions);
if (runInstancesResponse.getStatusCode() != 200) {
throw new ServiceException("查询实例状态失败");
}
log.info("实例创建成功: {}", runInstancesResponse.getBody().getInstanceIdSets().instanceIdSet);
RunInstancesResponseBody body = runInstancesResponse.getBody();
RunInstancesResponseBody.RunInstancesResponseBodyInstanceIdSets instanceIdSets = body.getInstanceIdSets();
return new ArrayList<>(instanceIdSets.instanceIdSet);
} catch (Exception error) {
log.error("创建阿里云实例报错:[{}]", error.getMessage());
throw new ServiceException(error.getMessage());
}
}
/**
* id
*
* @param instanceIds id
*/
public List<AliInstance> selectInstance(List<String> instanceIds) throws Exception {
// 检查实例ID列表是否为空如果为空则抛出异常
if (instanceIds == null || instanceIds.isEmpty()) {
throw new ServiceException("实例id不能为空");
}
// 创建查询实例的请求对象
DescribeInstancesRequest request = new DescribeInstancesRequest()
.setRegionId(aliProperties.getRegionId());
// 创建运行时选项对象,用于配置请求的额外参数
RuntimeOptions runtimeOptions = new RuntimeOptions();
List<AliInstance> aliInstances = new ArrayList<>();
List<String> stringArrayList = new ArrayList<>();
try {
// 发送请求并获取响应对象
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(request, runtimeOptions);
// 检查响应状态码如果为200则表示查询失败抛出异常
if (describeInstancesResponse.getStatusCode() != 200) {
throw new ServiceException("查询实例状态失败");
}
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instance = describeInstancesResponse.getBody().getInstances().getInstance();
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance bodyInstance : instance) {
// 实例id
String instanceId = bodyInstance.getInstanceId();
log.info("实例id为{}", instanceId);
// ip地址
String ipAddress = bodyInstance.getPublicIpAddress().getIpAddress().get(0);
log.info("实例ip为{}", ipAddress);
stringArrayList.add(ipAddress);
// 实例状态
String status = bodyInstance.getStatus();
log.info("实例状态为:{}", status);
AliInstance aliInstance = new AliInstance(instanceId, ipAddress, status);
aliInstances.add(aliInstance);
redisService.setCacheList(instanceId,aliInstances);
aliInstances.remove(aliInstance);
}
log.info("======================ipList{}",stringArrayList);
redisService.setCacheList("oneIpList",stringArrayList);
log.info("查询成功");
} catch (Exception e) {
log.error("查询服务器实例错误:[{}]", e.getMessage(), e);
throw new RuntimeException(e);
}
return aliInstances;
}
/**
*
*/
public void deleteInstance() throws Exception {
DescribeInstancesRequest attributeRequest = new DescribeInstancesRequest();
attributeRequest.setRegionId(aliProperties.getRegionId());
RuntimeOptions runtimeOptions = new RuntimeOptions();
DescribeInstancesResponse instancesWithOptions = client.describeInstancesWithOptions(attributeRequest, runtimeOptions);
ArrayList<String> list = new ArrayList<>();
DescribeInstancesResponseBody body = instancesWithOptions.getBody();
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : body.instances.instance) {
list.add(instance.getInstanceId());
}
log.info("list:" + list);
DeleteInstancesRequest deleteInstancesRequest = new DeleteInstancesRequest();
deleteInstancesRequest.setRegionId(aliProperties.getRegionId())
.setDryRun(false)
.setForce(true)
.setTerminateSubscription(true)
.setInstanceId(list);
RuntimeOptions runtime = new RuntimeOptions();
try {
client.deleteInstancesWithOptions(deleteInstancesRequest, runtime);
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}

View File

@ -0,0 +1,51 @@
package com.muyu.cloud.vehicle.gateway.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
*
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyun")
public class AliProperties {
/**
* Key
*/
private String accessKeyId;
/**
* Secret
*/
private String accessKeySecret;
/**
*
*/
private String endpoint;
/**
* ID
*/
private String regionId;
/**
* ID
*/
private String imageId;
/**
*
*/
private String instanceType;
/**
* ID
*/
private String securityGroupId;
/**
* ID
*/
private String switchId;
/**
*
*/
private Integer amount;
}

View File

@ -0,0 +1,186 @@
package com.muyu.cloud.vehicle.gateway.config;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Exchanger;
/**
* rabbitmq
*/
@Log4j2
@Configuration
public class RabbitmqConfig {
/**
*
*/
private static final Logger logger = LoggerFactory.getLogger(RabbitmqConfig.class);
/**
*
*/
public static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";
/**
* 线vin
*/
public static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
/**
*
*/
public static final String QUEUE_INFORM_SMS = "queue_inform_sms";
/**
* 线vin
*/
public static final String QUEUE_INFORM_SEND = "queue_inform_send";
/**
* saas
*/
public static final String QUEUE_INFORM_SAAS = "queue_inform_saas";
/**
* key 线
*/
public static final String ROUTINGKEY_EMAIL = "inform.#.email.#";
/**
* key
*/
public static final String ROUTINGKEY_SMS = "inform.#.sms.#";
/**
* key 线
*/
public static final String ROUTINGKEY_SEND = "inform.#.send.#";
/**
* key saas
*/
public static final String ROUTINGKEY_SAAS = "inform.#.saas.#";
/**
* ,
*/
@Bean(EXCHANGE_TOPICS_INFORM)
public Exchange exchangeTopicsInform() {
try {
Exchange exchange = ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build();
log.info("创建的交换机为: {}", EXCHANGE_TOPICS_INFORM);
return exchange;
} catch (Exception e) {
log.error("创建该: {} 交换机失败", EXCHANGE_TOPICS_INFORM, e);
throw e;
}
}
/**
* QUEUE_INFORM_EMAIL
*/
@Bean(QUEUE_INFORM_EMAIL)
public Queue queueInformEmail() {
try {
Queue queue = new Queue(QUEUE_INFORM_EMAIL);
log.info("创建的队列为: {}", QUEUE_INFORM_EMAIL);
return queue;
} catch (Exception e) {
log.error("创建该: {} 队列失败", QUEUE_INFORM_EMAIL, e);
throw e;
}
}
/**
* QUEUE_INFORM_SMS
*/
@Bean(QUEUE_INFORM_SMS)
public Queue queueInformSms() {
try {
Queue queue = new Queue(QUEUE_INFORM_SMS);
log.info("创建的队列为: {}", QUEUE_INFORM_SMS);
return queue;
} catch (Exception e) {
log.error("创建该: {} 队列失败", QUEUE_INFORM_SMS, e);
throw e;
}
}
/**
* QUEUE_INFORM_SEND
*/
@Bean(QUEUE_INFORM_SEND)
public Queue queueInformSend() {
try {
Queue queue = new Queue(QUEUE_INFORM_SEND);
log.info("创建的队列为: {}", QUEUE_INFORM_SEND);
return queue;
} catch (Exception e) {
log.error("创建该: {} 队列失败", QUEUE_INFORM_SEND, e);
throw e;
}
}
/**
* QUEUE_INFORM_SAAS
*/
@Bean(QUEUE_INFORM_SAAS)
public Queue queueInformSaas() {
try {
Queue queue = new Queue(QUEUE_INFORM_SAAS);
log.info("创建的队列为: {}", QUEUE_INFORM_SAAS);
return queue;
} catch (Exception e) {
log.error("创建该: {} 队列失败", QUEUE_INFORM_SAAS, e);
throw e;
}
}
/**
* QUEUE_INFORM_EMAILroutingKey ROUTINGKEY_EMAIL
*
* @param queue QUEUE_INFORM_EMAIL
* @param exchange EXCHANGE_TOPICS_INFORM
*/
@Bean
public Binding bindingQueueInformEmail(@Qualifier(QUEUE_INFORM_EMAIL) Queue queue,
@Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_EMAIL).noargs();
}
/**
* QUEUE_INFORM_SMS routingKey ROUTINGKEY_SMS
*
* @param queue QUEUE_INFORM_SMS
* @param exchange EXCHANGE_TOPICS_INFORM
*/
@Bean
public Binding bindingRoutingKeySms(@Qualifier(QUEUE_INFORM_SMS) Queue queue,
@Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_SMS).noargs();
}
/**
* QUEUE_INFORM_SENDroutingKey ROUTINGKEY_SEND
*
* @param queue QUEUE_INFORM_SEND
* @param exchange EXCHANGE_TOPICS_INFORM
*/
@Bean
public Binding bindingRoutingKeySend(@Qualifier(QUEUE_INFORM_SEND) Queue queue,
@Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_SEND).noargs();
}
/**
* QUEUE_INFORM_SAASroutingKey ROUTINGKEY_SAAS
*
* @param queue QUEUE_INFORM_SAAS
* @param exchange EXCHANGE_TOPICS_INFORM
*/
@Bean
public Binding bindingRoutingKeySaas(@Qualifier(QUEUE_INFORM_SAAS) Queue queue,
@Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_SAAS).noargs();
}
}

View File

@ -0,0 +1,40 @@
package com.muyu.cloud.vehicle.gateway.controller;
import com.muyu.cloud.vehicle.gateway.domain.model.MqttServerModel;
import com.muyu.cloud.vehicle.gateway.domain.req.VehicleConnectionReq;
import com.muyu.cloud.vehicle.gateway.service.VehicleConnectionService;
import com.muyu.common.core.domain.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*
*
*/
@Log4j2
@RestController
@RequestMapping("/vehicleGateway")
@Tag(name = "连接车辆控制层")
public class VehicleConnectionController {
@Autowired
private VehicleConnectionService vehicleConnectionService;
/**
* http
* @param vehicleConnectionReq
* @return
*/
@PostMapping("/receiveMsg/connect")
public Result<MqttServerModel> receiveMsg(@RequestBody VehicleConnectionReq vehicleConnectionReq){
log.info("===============>"+vehicleConnectionReq);
return vehicleConnectionService.getConnect(vehicleConnectionReq);
}
}

View File

@ -0,0 +1,23 @@
package com.muyu.cloud.vehicle.gateway.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AliInstance {
/**
* ID
*/
private String instanceId;
/**
* IP
*/
private String ipAddress;
/**
*
*/
private String status;
}

View File

@ -0,0 +1,42 @@
package com.muyu.cloud.vehicle.gateway.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AliServerConfig {
/**
*
*/
private Long id;
/**
* ID
*/
private String regionId;
/**
* ID
*/
private String imageId;
/**
*
*/
private String instanceType;
/**
* ID
*/
private String securityGroupId;
/**
* ID
*/
private String vSwitchId;
}

View File

@ -0,0 +1,23 @@
package com.muyu.cloud.vehicle.gateway.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ConnectWeight {
/**
* ID
*/
private String carServerId;
/**
*
*/
private Integer weightValue;
}

View File

@ -0,0 +1,51 @@
package com.muyu.cloud.vehicle.gateway.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName(value = "server_config")
public class ServerConfig {
/**
*
*/
@TableId(value = "id",type = IdType.AUTO)
private Long id;
/**
* id
*/
private String tenantId;
/**
*
*/
private String host;
/**
*
*/
private String port;
/**
*
*/
private String url;
/**
* MQTT
*/
private String defaultMqttAddr;
/**
* MQTT
*/
private String defaultMqttTopic;
/**
* MQTT QOS
*/
private Integer defaultMqttQos;
}

View File

@ -0,0 +1,34 @@
package com.muyu.cloud.vehicle.gateway.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class VehicleConnection {
/**
* VIN
*/
private String vehicleVin;
/**
*
*/
private String timestamp;
/**
*
*/
private String username;
/**
*
*/
private String nonce;
/**
*
*/
private String password;
}

View File

@ -0,0 +1,23 @@
package com.muyu.cloud.vehicle.gateway.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* VIN
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class VinIp {
/**
* vin
*/
String vin;
/**
* ip
*/
String ip;
}

View File

@ -0,0 +1,24 @@
package com.muyu.cloud.vehicle.gateway.domain.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ DescriptionMqtt
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class MqttServerModel {
/**
* Mqtt
*/
private String broker;
/**
* MQTT
*/
private String topic;
}

View File

@ -0,0 +1,42 @@
package com.muyu.cloud.vehicle.gateway.domain.properties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @ DescriptionMqtt
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MqttProperties implements Serializable {
/**
*
*/
private String broker;
/**
*
*/
private String topic;
/**
*
*/
private String userName;
/**
*
*/
private String password;
/**
* id
*/
private String clientId;
/**
*
*/
private int qos = 0;
}

View File

@ -0,0 +1,37 @@
package com.muyu.cloud.vehicle.gateway.domain.req;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class VehicleConnectionReq {
/**
* vin
*/
private String vehicleVin;
/**
*
*/
private String timestamp;
/**
*
*/
private String username;
/**
*
*/
private String nonce;
}

View File

@ -0,0 +1,32 @@
package com.muyu.cloud.vehicle.gateway.domain.resp;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
/**
* @ DescriptionAli
*/
@Data
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class AliServerConfig {
/**
*
*/
private Long id;
/**
* id (ID)
*/
private String regionId;
/**
* id
*/
private String imageId;
/**
* ()
*/
private String instanceType;
}

View File

@ -0,0 +1,15 @@
package com.muyu.cloud.vehicle.gateway.mapper;
import com.muyu.cloud.vehicle.gateway.domain.VehicleConnection;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface VehicleConnectionMapper {
void addConnect(VehicleConnection vehicleConnection);
List<String> selectByVehicleVin(String vehicleVin);
List<VehicleConnection> getMqttServerModel(String vehicleVin);
}

View File

@ -0,0 +1,15 @@
package com.muyu.cloud.vehicle.gateway.service;
import com.muyu.cloud.vehicle.gateway.domain.model.MqttServerModel;
import com.muyu.cloud.vehicle.gateway.domain.req.VehicleConnectionReq;
import com.muyu.common.core.domain.Result;
public interface VehicleConnectionService {
/**
*
* @param vehicleConnectionReq
* @return
*/
Result<MqttServerModel> getConnect(VehicleConnectionReq vehicleConnectionReq);
}

View File

@ -0,0 +1,150 @@
package com.muyu.cloud.vehicle.gateway.service.impl;
import com.muyu.cloud.vehicle.gateway.domain.VehicleConnection;
import com.muyu.cloud.vehicle.gateway.domain.VinIp;
import com.muyu.cloud.vehicle.gateway.domain.model.MqttServerModel;
import com.muyu.cloud.vehicle.gateway.domain.properties.MqttProperties;
import com.muyu.cloud.vehicle.gateway.domain.req.VehicleConnectionReq;
import com.muyu.cloud.vehicle.gateway.mapper.VehicleConnectionMapper;
import com.muyu.cloud.vehicle.gateway.service.VehicleConnectionService;
import com.muyu.common.core.domain.Result;
import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import static com.muyu.cloud.vehicle.gateway.config.RabbitmqConfig.*;
@Log4j2
@Service
public class VehicleConnectionServiceImpl implements VehicleConnectionService {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private VehicleConnectionMapper vehicleConnectionMapper;
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private RedisService redisService;
/**
*
* @param vehicleConnectionReq
* @return
*/
@Override
public Result<MqttServerModel> getConnect(VehicleConnectionReq vehicleConnectionReq) {
log.info("车辆连接请求:{}",vehicleConnectionReq.toString());
// 使用交换机发送消息
// rabbitTemplate.convertAndSend("exchange_topics_inform","inform.#.email.#",vehicleConnectionReq.getVehicleVin());
// log.info("发送消息成功:{}",vehicleConnectionReq.getVehicleVin());
VehicleConnection vehicleConnection = new VehicleConnection();
//车辆vin
vehicleConnection.setVehicleVin(vehicleConnectionReq.getVehicleVin());
//用户名
vehicleConnection.setUsername(vehicleConnectionReq.getUsername());
//密码(vin+时间戳+随机数)
vehicleConnection.setPassword(vehicleConnectionReq.getVehicleVin()+vehicleConnectionReq.getTimestamp()+vehicleConnectionReq.getNonce());
//查询有没有这辆车的vin码
List<String> selectVehicle = vehicleConnectionMapper.selectByVehicleVin(vehicleConnectionReq.getVehicleVin());
if(selectVehicle.isEmpty()){
//添加连接信息
vehicleConnectionMapper.addConnect(vehicleConnection);
log.info("车辆上线成功");
}else {
throw new RuntimeException("车辆无法重复预上线");
}
//先判断vin码
if(redisService.hasKey(vehicleConnection.getVehicleVin())){
log.error("============车辆:{}已经绑定过了",vehicleConnectionReq.getVehicleVin());
throw new RuntimeException("=============车辆已经绑定过了");
}
MqttProperties mqttProperties = new MqttProperties();
List<VehicleConnection> vehicleVin = selectByVehicleVin(vehicleConnectionReq.getVehicleVin());
for (VehicleConnection connection : vehicleVin) {
mqttProperties.setClientId(connection.getVehicleVin());
mqttProperties.setUserName(connection.getUsername());
mqttProperties.setPassword(connection.getPassword());
}
mqttProperties.setTopic("vehicle");
mqttProperties.setQos(0);
// //使用交换机发送消息
// rabbitTemplate.convertAndSend(EXCHANGE_TOPICS_INFORM,QUEUE_INFORM_EMAIL,mqttProperties);
// log.info("==============发送消息成功:{}",mqttProperties);
//判断redis有没有count键
if(redisTemplate.hasKey("oneCount")){
//取出count
Integer count = Integer.valueOf(redisTemplate.opsForValue().get("oneCount"));
if(count == 1){
redisTemplate.opsForValue().set("oneCount",String.valueOf(0));
}else {
redisTemplate.opsForValue().set("oneCount",String.valueOf(count+1));
}
//根据游标count获取服务IP
Object ipList = redisService.redisTemplate.opsForList().index("oneIpList", count);
log.info("=========================oneIpList:"+ipList);
//关联车辆和服务
this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ipList.toString()));
//响应信息
log.info("车辆:{}",vehicleConnectionReq.getVehicleVin()+"绑定成功:{}",ipList);
mqttProperties.setBroker("tcp://"+ipList+":1883");
//使用交换机发送消息
rabbitTemplate.convertAndSend(EXCHANGE_TOPICS_INFORM,ROUTINGKEY_SMS,mqttProperties);
log.info("==================发送消息成功:{}",mqttProperties);
return Result.success(new MqttServerModel("tcp://"+ipList+":1883","vehicle"));
}else {
redisTemplate.opsForValue().set("oneCount",String.valueOf(0));
//根据游标count获取服务器Ip
// String ip = redisTemplate.opsForList().index("ipList", 0);
Object ipList = redisService.redisTemplate.opsForList().index("oneIpList", 0);
//关联车辆和服务
this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ipList.toString()));
//响应信息
log.info("车辆:{}",vehicleConnectionReq.getVehicleVin(),"与:{}绑定成功",ipList);
mqttProperties.setBroker("tcp://"+ipList+":1883");
//使用交换机发送消息
rabbitTemplate.convertAndSend(EXCHANGE_TOPICS_INFORM,ROUTINGKEY_SMS,mqttProperties);
log.info("================发送消息成功:{}",mqttProperties);
return Result.success(new MqttServerModel("tcp://"+ipList+":1883","vehicle"));
}
}
/**
*
* @param vehicleVin vin
* @return
*/
private List<VehicleConnection> selectByVehicleVin(String vehicleVin) {
return vehicleConnectionMapper.getMqttServerModel(vehicleVin);
}
/**
* IPredis
*/
public void addIpAddress(VinIp vinIp) {
if (vinIp == null || vinIp.getVin() == null || vinIp.getVin().isEmpty() || vinIp.getIp() == null || vinIp.getIp().isEmpty()) {
throw new IllegalArgumentException("vin 或 ip 不能为空或无效");
}
redisService.setCacheObject(vinIp.getVin(), vinIp.getIp());
}
}

View File

@ -1,108 +0,0 @@
// This file is auto-generated, don't edit it. Thanks.
package com.muyu.cloud.vehicle.gateway.test.example;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.aliyun.tea.*;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
/**
*
*/
@Log4j2
@Component
public class DelInstance implements DisposableBean{
/**
* <b>description</b> :
* <p>使AK&amp;SKClient</p>
* @return Client
*
* @throws Exception
*/
public static com.aliyun.ecs20140526.Client createClient() throws Exception {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
// 建议使用更安全的 STS 方式更多鉴权访问方式请参见https://help.aliyun.com/document_detail/378657.html。
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
.setAccessKeyId("LTAI5t7Fnx2QLTYLSu9357wP")
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
.setAccessKeySecret("3LOnydNZ25ytsTGczuSygElx0HJ6nN");
// Endpoint 请参考 https://api.aliyun.com/product/Ecs
config.endpoint = "ecs.cn-shanghai.aliyuncs.com";
return new com.aliyun.ecs20140526.Client(config);
}
public static void delInstance() throws Exception{
//创建ECS客户端对象用于后续调用ECS相关API
com.aliyun.ecs20140526.Client client = DelInstance.createClient();
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
.setRegionId("cn-shanghai");
//创建运行时选择对象,用于配置运行时的选项参数
RuntimeOptions runtimeOptions = new RuntimeOptions();
//获取实例列表
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtimeOptions);
//提取实例ID集合
ArrayList<String> list = new ArrayList<>();
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : body.getInstances().getInstance()) {
list.add(instance.getInstanceId());
}
System.out.println("Instance IDs"+list);
// 创建删除实例请求对象,并设置请求参数
com.aliyun.ecs20140526.models.DeleteInstancesRequest deleteInstancesRequest = new com.aliyun.ecs20140526.models.DeleteInstancesRequest()
// 设置地域ID指定要删除的实例所属的地域ID。
.setRegionId("cn-shanghai")
//设置DryRun为True用于验证请求是否可以成功但不实际执行删除操作
.setDryRun(false)
// 设置Force为true表示即使实例有正在运行的任务也强制删除实例
.setForce(true)
// 设置TerminateSubscription为true表示删除按订阅付费的实例时终止订阅
.setTerminateSubscription(true)
// 设置实例ID列表使用参数名称 instanceId参数类型为数组。
.setInstanceId(list);
// 创建运行时选项对象,用于配置运行时的选项参数
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try{
//复制代码运行请自行打印 API 的返回值
client.deleteInstancesWithOptions(deleteInstancesRequest,runtime);
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error){
TeaException error = new TeaException(_error.getMessage(), _error);
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
//诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
@Override
public void destroy() throws Exception {
log.info("===============>开始执行删除实例方法");
delInstance();
}
}

Some files were not shown because too many files have changed in this diff Show More