Compare commits

..

No commits in common. "master" and "master_suzejing" have entirely different histories.

40 changed files with 472 additions and 2037 deletions

103
pom.xml
View File

@ -38,7 +38,6 @@
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<mqttv3.version>1.2.5</mqttv3.version>
<spring-kafka.version>2.8.0</spring-kafka.version>
<aliyun.ecs.version>3.1.12</aliyun.ecs.version>
</properties>
<!-- 依赖声明 -->
@ -264,17 +263,7 @@
<artifactId>zhilian-common-business</artifactId>
<version>${zhilian.version}</version>
</dependency>
<!-- 阿里云ESC服务版本控制-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>ecs20140526</artifactId>
<version>${aliyun.ecs.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
@ -328,57 +317,57 @@
</executions>
</plugin>
<!-- 要将源码放上去,需要加入这个插件 -->
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-source-plugin</artifactId>-->
<!-- <version>3.0.1</version>-->
<!-- <configuration>-->
<!-- <attach>true</attach>-->
<!-- </configuration>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <phase>compile</phase>-->
<!-- <goals>-->
<!-- <goal>jar</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<!-- <distributionManagement>-->
<!-- <repository>-->
<!-- <id>releases</id>-->
<!-- <name>releases</name>-->
<!-- <url>http://nexus.zhilian.com:8081/repository/maven-releases/</url>-->
<!-- </repository>-->
<!-- </distributionManagement>-->
<distributionManagement>
<repository>
<id>releases</id>
<name>releases</name>
<url>http://nexus.zhilian.com:8081/repository/maven-releases/</url>
</repository>
</distributionManagement>
<!-- <repositories>-->
<!-- <repository>-->
<!-- <id>public</id>-->
<!-- <name>aliyun nexus</name>-->
<!-- <url>http://nexus.zhilian.com:8081/repository/maven-public/</url>-->
<!-- <releases>-->
<!-- <enabled>true</enabled>-->
<!-- </releases>-->
<!-- </repository>-->
<!-- </repositories>-->
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://nexus.zhilian.com:8081/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<!-- <pluginRepositories>-->
<!-- <pluginRepository>-->
<!-- <id>public</id>-->
<!-- <name>aliyun nexus</name>-->
<!-- <url>http://nexus.zhilian.com:8081/repository/maven-public/</url>-->
<!-- <releases>-->
<!-- <enabled>true</enabled>-->
<!-- </releases>-->
<!-- <snapshots>-->
<!-- <enabled>false</enabled>-->
<!-- </snapshots>-->
<!-- </pluginRepository>-->
<!-- </pluginRepositories>-->
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://nexus.zhilian.com:8081/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

@ -156,13 +156,13 @@ public class RedisService {
/**
* Set
*
* @param key
* @param key
* @param setValue
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final T setValue) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
setOperation.add(setValue);
setOperation.add(setValue);
return setOperation;
}
@ -272,6 +272,8 @@ public class RedisService {
}
/**
* Zset
*
@ -308,7 +310,6 @@ public class RedisService {
/**
*
*
* @param zkey
* @param start
* @param end
@ -328,50 +329,46 @@ public class RedisService {
/**
* ,delta,
*
* @param zkey
* @param value
* @param delta
* @param <T>
*/
public <T> Double incrementScore(final String zkey, final T value, final Double delta) {
return redisTemplate.opsForZSet().incrementScore(zkey, value, delta);
public <T> Double incrementScore(final String zkey, final T value, final Double delta){
return redisTemplate.opsForZSet().incrementScore(zkey,value,delta);
}
/**
*
*
* @param zkey
* @param values
* @param <T>
* @return
* @param <T>
*/
public <T> Long removeCacheZsetBatch(final String zkey, final T... values) {
return redisTemplate.opsForZSet().remove(zkey, values);
public <T> Long removeCacheZsetBatch(final String zkey,final T... values){
return redisTemplate.opsForZSet().remove(zkey,values);
}
/**
* ,
*
* @param zkey
* @param start
* @param end
* @return
*/
public Set<Double> reverseRange(final String zkey, final Long start, final Long end) {
return redisTemplate.opsForZSet().reverseRange(zkey, start, end);
public Set<Double> reverseRange(final String zkey,final Long start,final Long end){
return redisTemplate.opsForZSet().reverseRange(zkey,start,end);
}
/**
*
*
* @param zkey
* @param min
* @param max
* @return
*/
public Set<Double> rangeByScore(final String zkey, final Double min, final Double max) {
return redisTemplate.opsForZSet().rangeByScore(zkey, min, max);
public Set<Double> rangeByScore(final String zkey,final Double min,final Double max){
return redisTemplate.opsForZSet().rangeByScore(zkey,min,max);
}
/**
@ -380,7 +377,7 @@ public class RedisService {
* @param zkey
* @return
*/
public ZSetOperations.TypedTuple getCacheZsetMin(final String zkey) {
public ZSetOperations.TypedTuple getCacheZsetMin(final String zkey){
ZSetOperations.TypedTuple typedTuple = redisTemplate.opsForZSet().popMin(zkey);
return typedTuple;
}
@ -396,43 +393,13 @@ public class RedisService {
return redisTemplate.keys(pattern);
}
public void deleteCacheSet(final String key) {
public void deleteCacheSet(String key) {
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.remove(key);
}
public <T> void deleteCacheSetValue(final String key, final T value) {
public <T> void deleteCacheSetValue(String key, T value) {
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.remove(key, value);
}
public <T> void deleteCacheZsetValue(final String key, final T value) {
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
zSetOperations.remove(key, value);
}
/**
* @description: Listvalue
* @author: LiYuan
* @param: key index
* @return: value
**/
public <T> T getcacheListValue(final String key, final Long index) {
ListOperations listOperations = redisTemplate.opsForList();
return (T) listOperations.index(key, index);
}
/**
* @description: String
* @author: LiYuan
* @param: key,number
* @return: Long
**/
public Long increment(final String key,final Long number) {
ValueOperations valueOperations = redisTemplate.opsForValue();
return valueOperations.increment(key,number);
setOperations.remove(key,value);
}
}

View File

@ -98,18 +98,12 @@
<artifactId>spring-kafka</artifactId>
</dependency>
<!-- 业务系统远程调用-->
<dependency>
<groupId>com.zhilian</groupId>
<artifactId>zhilian-common-business</artifactId>
</dependency>
<!-- 阿里云Ecs服务依赖(openAPI)-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>ecs20140526</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -1,46 +0,0 @@
package com.zhilian.online.Timer;
import com.zhilian.online.uitls.AliyunOpenAPIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.Timer
* @Author: LiYuan
* @CreateTime: 2024-04-17 21:53
* @Description:
* @Option:
* @Version: 1.0
*/
@Component
@Slf4j
public class LoadObserver {
/**
* api
*/
@Autowired
private AliyunOpenAPIUtils aliyunOpenAPIUtils;
/**
*
*/
@Scheduled(cron = "0/10 * * * * ?")
public void addInstance(){
}
/**
*
*/
@Scheduled(cron = "0/10 * * * * ?")
public void ReduceInstance(){
}
}

View File

@ -4,18 +4,11 @@ import com.zhilian.common.security.annotation.EnableCustomConfig;
import com.zhilian.common.security.annotation.EnableMyFeignClients;
import com.zhilian.common.swagger.annotation.EnableCustomSwagger2;
import com.zhilian.online.controller.OnlineLoadCenterController;
import com.zhilian.online.domain.EcsInstance;
import com.zhilian.online.domain.req.EcsCreateReq;
import com.zhilian.online.uitls.AliyunOpenAPIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import java.util.List;
/**
* @version:
@ -27,45 +20,9 @@ import java.util.List;
@EnableCustomSwagger2
@EnableMyFeignClients
@SpringBootApplication
@Slf4j
public class ZhiLianOnlineApplication implements ApplicationRunner {
@Autowired
private AliyunOpenAPIUtils aliyunOpenAPIUtils;
public class ZhiLianOnlineApplication{
public static void main(String[] args) {
SpringApplication.run(ZhiLianOnlineApplication.class, args);
SpringApplication.run(ZhiLianOnlineApplication.class,args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("项目启动,调用创建实例方法");
RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk();
systemDisk = systemDisk.setSize("20").setCategory("cloud_efficiency");
EcsCreateReq ecs = EcsCreateReq.builder()
.regionId("cn-zhangjiakou")
.imageId("m-8vbfx0e48cekro0f13bx")
.instanceType("ecs.t6-c1m1.large")
.securityGroupId("sg-8vb49jd1c1lsa3akwo02")
.vSwitchId("vsw-8vb0krtyfdmb27nhcmzc2")
.instanceName("gather-node")
.internetMaxBandwidthIn(80)
.internetMaxBandwidthOut(10)
.uniqueSuffix(true)
.password("142730.Ly")
.zoneId("cn-zhangjiakou-c")
.internetChargeType("PayByTraffic")
.systemDiskSize("20")
.systemDickCategory("cloud_efficiency")
.amount(1)
.minAmount(1)
.periodUnit("Week")
.period(1)
.instanceChargeType("PostPaid")
// .privateIpAddress("10.10.27.1")
.build();
List<String> instance = aliyunOpenAPIUtils.createInstance(ecs);
List<EcsInstance> ecsInstances = aliyunOpenAPIUtils.queryEcsInstances(instance);
log.info("创建的实例信息为{}" , ecsInstances);
}
}

View File

@ -1,70 +0,0 @@
package com.zhilian.online.config;
import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.config
* @Author: LiYuan
* @CreateTime: 2024-04-12 14:43
* @Description: Ecs
* @Version: 1.0
*/
@Configuration
@ConfigurationProperties("aliyun.ecs")
@Data
@Slf4j
public class AliyunEcsConfig {
/**
*
*/
private String accessKeyId;
/**
*
*/
private String accessKeySecret;
/**
*
*/
private String endpoint;
/**
*
*/
private String regionId;
/**
* 使AK&SKClient
* @return Client
* @throws Exception
*/
@Bean()
public Client createClient() throws Exception {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
// 建议使用更安全的 STS 方式更多鉴权访问方式请参见https://help.aliyun.com/document_detail/378657.html。
Config config = new Config()
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
.setAccessKeyId(accessKeyId)
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
.setAccessKeySecret(accessKeySecret)
.setRegionId(regionId);
// Endpoint 请参考 https://api.aliyun.com/product/Ecs
config.endpoint = endpoint;
Client aliyunClient = new Client(config);
return aliyunClient;
}
}

View File

@ -100,7 +100,7 @@ public class MqttxConfig {
// @PostConstruct
@PostConstruct
public void initMqtt() {
log.info("mqttx连接中......");

View File

@ -16,7 +16,7 @@ public class OnlineConstants {
/**
*
*/
public static final String NODE_TOKEN_PREFIX = "node_token:";
public static final String ONLINE_TOKEN_PREFIX = "online_token:";
/**
*
@ -26,26 +26,11 @@ public class OnlineConstants {
/**
*
*/
public static final String GATHER_LOAD_PREFIX = "gather:load:";
public static final String GATHER_LOAD_CONTROL = "gather_info_control";
/**
* 线
*
*/
public static final String ONLINE_GATHER_PREFIX = "online_vehicle:";
/**
* http
*/
public static final String HTTP_PREFIX = "http://";
/**
* https
*/
public static final String HTTPS_PREFIX = "https://";
/**
* fluxMQ
*/
public static final String FLUXMQ_INFO_URL = ":8080/public/cluster";
public static final String ONLINE_VEHICLE = "online_vehicle:";

View File

@ -1,19 +1,25 @@
package com.zhilian.online.consumer;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonObject;
import com.alibaba.fastjson.JSON;
import com.zhilian.common.core.constant.Constants;
import com.zhilian.common.core.domain.Result;
import com.zhilian.common.redis.service.RedisService;
import com.zhilian.online.config.RabbitConfig;
import com.zhilian.online.constans.OnlineConstants;
import com.zhilian.online.domain.model.GatewayNodeInfo;
import com.zhilian.online.load.cache.GatewayNodeInfoCache;
import com.zhilian.online.load.cache.GatewayNodeWeightCache;
import com.zhilian.online.domain.Gather;
import com.zhilian.online.domain.req.GatherRegReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @BelongsProject: smart-cloud-server
@ -33,26 +39,19 @@ public class DeadQueueConsumer {
@Autowired
private RedisService redisService;
@Autowired
private GatewayNodeInfoCache gatewayNodeInfoCache;
@Autowired
private GatewayNodeWeightCache gatewayNodeWeightCache;
/**
* ,线
* fluxMQhttp,线
*/
// @RabbitListener(queues = RabbitConfig.DEAD_QUEUE_NAME)
@RabbitListener(queues = RabbitConfig.DEAD_QUEUE_NAME)
public void SecureOnline(String gatherMsg) {
Gather gather = JSON.parseObject(gatherMsg, Gather.class);
log.info("开始检查节点{}的上线状态......", gatherMsg);
GatewayNodeInfo gatewayNodeInfo = JSONObject.parseObject(gatherMsg, GatewayNodeInfo.class);
String ipAddress = "";
String ipAddress = gather.getIpAddress();
HttpURLConnection connection = null;
try {
ipAddress = OnlineConstants.HTTP_PREFIX + ipAddress + OnlineConstants.FLUXMQ_INFO_URL;
ipAddress = "http://" + ipAddress;
URL url = new URL(ipAddress);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
@ -63,10 +62,10 @@ public class DeadQueueConsumer {
}
if (Constants.FAIL == responseCode){
log.error("节点{}上线失败",gatherMsg);
//删除节点数据
gatewayNodeInfoCache.remove(gatewayNodeInfo.getNodeId());
//上线失败需要将该节点的负载均衡缓存删除
gatewayNodeWeightCache.remove(gatewayNodeInfo);
if (redisService.hasKey(OnlineConstants.ONLINE_TOKEN_PREFIX + gather.getClientId())){
redisService.removeCacheZsetBatch(OnlineConstants.ONLINE_TOKEN_PREFIX + gather.getClientId());
}
}
} catch (Exception e) {
log.error("节点上线失败{}",e.getMessage());

View File

@ -0,0 +1,32 @@
package com.zhilian.online.controller;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.service.OnlineGatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 20:46
*/
@RestController
@RequestMapping("/gather")
public class OnlineGatherController {
/**
*
*/
@Autowired
private OnlineGatherService onlineGatherService;
}

View File

@ -5,7 +5,7 @@ import com.zhilian.common.core.domain.Result;
import com.zhilian.common.core.utils.ip.IpUtils;
import com.zhilian.common.core.web.controller.BaseController;
import com.zhilian.online.domain.ApifoxModel;
import com.zhilian.online.domain.Gather;
import com.zhilian.online.service.OnlineLoadCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -45,9 +45,9 @@ public class OnlineLoadCenterController extends BaseController {
* @return: Result<OnlineAccount>
**/
@GetMapping("/applyForReg")
public Result<String> applyForReg(String clusterId) {
log.info("节点{}申请注册令牌",clusterId);
return onlineLoadCenterService.applyForReg(clusterId);
public Result<String> applyForReg(Gather gather) {
log.info("申请注册令牌{}", JSON.toJSONString(gather));
return onlineLoadCenterService.applyForReg(gather);
}
@ -58,9 +58,11 @@ public class OnlineLoadCenterController extends BaseController {
* @return: Result
**/
@PostMapping("/regGather")
public Result regGather(@Validated @RequestBody ApifoxModel apifoxModel) {
log.info("节点{}正在上线", JSON.toJSONString(apifoxModel));
return onlineLoadCenterService.regGather(apifoxModel);
public Result regGather(@Validated @RequestBody Gather gather) {
String ipAddr = IpUtils.getIpAddr(request);
gather.setIpAddress(ipAddr);
log.info("节点{}正在上线", JSON.toJSONString(gather));
return onlineLoadCenterService.regGather(gather);
}
@ -74,8 +76,7 @@ public class OnlineLoadCenterController extends BaseController {
*/
@GetMapping("/applyForConnectToGather")
public Result applyForConnectToGather(@RequestParam("vin") String vin) {
onlineLoadCenterService.applyForConnectToGather(vin);
return Result.success();
return Result.success(onlineLoadCenterService.applyForConnectToGather(vin));
}
/**

View File

@ -0,0 +1,49 @@
package com.zhilian.online.controller;/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/30 11:18
*/
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.domain.model.MqttServerModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.controller
* @Author: LiYuan
* @CreateTime: 2024-03-30 11:18
* @Description: 线
* @Version: 1.0
*/
@RestController
@RequestMapping("/verify")
public class OnlineVerifyController {
/**
* mqtt
*/
@Value("${mqtt.server.broker}")
private String broker;
/**
*
*/
@Value("${mqtt.server.topic}")
private String topic;
@PostMapping("/vehicleConnection")
public Result<MqttServerModel> vehicleConnection() {
return Result.success(
MqttServerModel.builder()
.broker(broker)
.topic(topic)
.build()
);
}
}

View File

@ -1,70 +0,0 @@
package com.zhilian.online.domain;
import lombok.Data;
@Data
public class ApifoxModel {
/**
* ID
*/
private String clusterId;
/**
* CPU使
*/
private CPUInfo cpuInfo;
/**
*
*/
private FlowInfo flowInfo;
/**
* HTTP
*/
private String httpUrl;
/**
* JVM使
*/
private JVMInfo jvmInfo;
/**
* MQTT
*/
private MqttInfo mqttInfo;
/**
* MQTTS
*/
private String mqttsUrl;
/**
* MQTT
*/
private String mqttUrl;
/**
*
*/
private String nodeName;
/**
*
*/
private String startJvmTime;
/**
*
*/
private String version;
/**
* websocket
*/
private String websocketUrl;
/**
*
*/
private String publicIpAddress;
/**
*
*/
private String privateIpAddress;
/**
*
*/
private String token;
}

View File

@ -1,30 +0,0 @@
package com.zhilian.online.domain;
import lombok.Data;
/**
* CPU使
*/
@Data
public class CPUInfo {
/**
* CPU
*/
private long cpuNum;
/**
* 使
*/
private String cSys;
/**
*
*/
private String idle;
/**
* I/O
*/
private String iowait;
/**
* 使
*/
private String user;
}

View File

@ -1,261 +0,0 @@
package com.zhilian.online.domain;
import lombok.*;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain
* @Author: LiYuan
* @CreateTime: 2024-04-12 15:01
* @Description: ECS
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class EcsInstance {
/**
* ISO 8601 使 UTC+0 yyyy-MM-ddTHH:mmZ
*/
private String creationTime;
/**
*
*/
private String serialNumber;
/**
*
*/
private String status;
/**
* ID
*/
private String deploymentSetId;
/**
*
*/
private String keyPairName;
/**
* :
* NoSpot
* SpotWithPriceLimit
* SpotAsPriceGo
*/
private String spotStrategy;
/**
*
*/
private Boolean deviceAvailable;
/**
* GiB
*/
private Long localStorageCapacity;
/**
*
*/
private String description;
/**
*
* 1 1 1
* 0 1
*/
private Integer spotDuration;
/**
*
* classic
* vpc VPC
*/
private String instanceNetworkType;
/**
*
*/
private String instanceName;
/**
* ID
*/
private String instanceId;
/**
*
*/
private String osNameEn;
/**
* HPC ID
*/
private String hpcClusterId;
/**
* 3 SpotStrategy=SpotWithPriceLimit
*/
private Number spotPriceLimit;
/**
* MiB
*/
private Integer memory;
/**
*
*/
private String osName;
/**
* ECS
*/
private String deploymentSetGroupNo;
/**
* ID
*/
private String imageId;
/**
* GPU
*/
private String gpuSpec;
/**
* APIDeleteInstance
* true
* false
*/
private Boolean deletionProtection;
/**
*
* KeepCharging
* StopCharging vCPU IP
* Not-applicable
*/
private String stoppedMode;
/**
* GPU
*/
private Integer gpuAmount;
/**
*
*/
private String hostName;
/**
* Mbit/s
*/
private Integer internetMaxBandwidthOut;
/**
* Mbit/s
*/
private Integer internetMaxBandwidthIn;
/**
*
*/
private String instanceType;
/**
*
* PrePaid
* PostPaid
*/
private String instanceChargeType;
/**
* ID
*/
private String regionId;
/**
* I/O
*/
private Boolean ioOptimized;
/**
* ISO 8601 使 UTC+0 yyyy-MM-ddTHH:mmZ
*/
private String startTime;
/**
* vCPU
*/
private Integer cpu;
/**
*
*/
private Integer localStorageAmount;
/**
* ISO 8601 使 UTC+0 yyyy-MM-ddTHH:mmZ
*/
private String expiredTime;
/**
*
*/
private String zoneId;
/**
*
*/
private Boolean recyclable;
/**
*
* Standard
* Unlimited
*/
private String creditSpecification;
/**
*
*/
private String instanceTypeFamily;
/**
* Windows Server Linux
* windows
* linux
*/
private String osType;
/**
* IP
*/
private String publicIpAddress;
/**
* IP
*/
private String privateIpAddress;
/**
* ID
*/
private String vpcId;
/**
* ID
*/
private List<String> securityGroupIds;
}

View File

@ -1,28 +0,0 @@
package com.zhilian.online.domain;
import lombok.Data; /**
*
*/
@Data
public class FlowInfo {
/**
*
*/
private String lastReadThroughput;
/**
*
*/
private String lastWriteThroughput;
/**
*
*/
private String readBytesHistory;
/**
*
*/
private String realWriteBytes;
/**
*
*/
private String writeBytesHistory;
}

View File

@ -0,0 +1,70 @@
package com.zhilian.online.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.zhilian.common.core.web.domain.BaseEntity;
import lombok.*;
import org.bouncycastle.util.IPAddress;
import javax.validation.constraints.NotBlank;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain
* @Author: LiYuan
* @CreateTime: 2024-03-31 08:58
* @Description:
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Gather extends BaseEntity {
/**
* ID
*/
private String clientId;
/**
*
*/
private String token;
/**
* broker
*/
@NotBlank
private String broker;
/**
* username
*/
private String username;
/**
* password
*/
private String password;
/**
* qos
*/
private Integer qos;
/**
* topic
*/
@NotBlank
private String topic;
/**
* ip
*/
private String ipAddress;
}

View File

@ -1,58 +0,0 @@
package com.zhilian.online.domain;
import lombok.Data;
/**
* JVM使
*/
@Data
public class JVMInfo {
/**
* ()
*/
private String fileDescriptors;
/**
*
*/
private String heapCommit;
/**
*
*/
private String heapInit;
/**
*
*/
private String heapMax;
/**
* 使
*/
private String heapUsed;
/**
* JAVA
*/
private String jdkHome;
/**
* JDK
*/
private String jdkVersion;
/**
*
*/
private String noHeapCommit;
/**
*
*/
private String noHeapInit;
/**
*
*/
private String noHeapMax;
/**
* 使
*/
private String noHeapUsed;
/**
* 线
*/
private long threadCount;
}

View File

@ -1,63 +0,0 @@
package com.zhilian.online.domain;// ApifoxModel.java
import lombok.Data;
// JVMInfo.java
// MqttInfo.java
/**
* MQTT
*/
@Data
public class MqttInfo {
/**
*
*/
private long closeEventSize;
/**
*
*/
private long connectEventSize;
/**
*
*/
private long connectSize;
/**
*
*/
private long disconnectEventSize;
/**
*
*/
private long publishEventSize;
/**
*
*/
private long publishRetryEventSize;
/**
*
*/
private long retainSize;
/**
*
*/
private long subscribeEventSize;
/**
*
*/
private long subscribeSize;
/**
*
*/
private long topicSize;
/**
*
*/
private long unSubscribeEventSize;
}

View File

@ -0,0 +1,37 @@
//package com.zhilian.online.domain;/**
// * @version:
// * @Author: LiYuan
// * @description:
// * @date: 2024/3/29 21:44
// */
//
//import com.baomidou.mybatisplus.annotation.IdType;
//import com.baomidou.mybatisplus.annotation.TableId;
//import com.baomidou.mybatisplus.annotation.TableName;
//import com.zhilian.common.core.web.domain.BaseEntity;
//import lombok.*;
//
//import javax.validation.constraints.NotBlank;
//import javax.validation.constraints.NotNull;
//import java.util.Date;
//
///**
// *@BelongsProject: smart-cloud-server
// *@BelongsPackage: com.zhilian.online.domain
// *@Author: LiYuan
// *@CreateTime: 2024-03-29 21:44
// *@Description: 汽车类,测试使用
// *@Version: 1.0
// */
//@Data
////@AllArgsConstructor
////@NoArgsConstructor
//@Builder
//@ToString
//@EqualsAndHashCode(callSuper = true)
//@TableName("vehicle")
//public class Vehicle extends BaseEntity {
//
//
//
//}

View File

@ -0,0 +1,70 @@
package com.zhilian.online.domain;/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 21:49
*/
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.zhilian.common.core.web.domain.BaseEntity;
import lombok.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
/**
*@BelongsProject: smart-cloud-server
*@BelongsPackage: com.zhilian.online.domain
*@Author: LiYuan
*@CreateTime: 2024-03-29 21:49
*@Description:
*@Version: 1.0
*/
@Data
@AllArgsConstructor
@NotBlank
@ToString
@EqualsAndHashCode(callSuper = true)
@TableName("vehicle_account")
public class VehicleAccount extends BaseEntity{
/**
* VIN
*/
@TableId(type = IdType.INPUT)
private String vin;
/**
*
*/
@NotNull
private Date applyTime;
/**
*
*/
@NotBlank
private String applyCode;
/**
*
*/
private String username;
/**
*
*/
private String password;
/**
* id
*/
private String clientId;
}

View File

@ -1,35 +0,0 @@
package com.zhilian.online.domain.model;
import lombok.*;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain.model
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:47
* @Description:
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class GatewayNodeInfo {
/**
* id
*/
private String nodeId;
/**
* IP
*/
private String publicIpAddress;
/**
* IP
*/
private String privateIpAddress;
}

View File

@ -1,123 +0,0 @@
package com.zhilian.online.domain.req;
import lombok.*;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain.req
* @Author: LiYuan
* @CreateTime: 2024-04-16 20:23
* @Description: openAPI
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class EcsCreateReq {
/**
*
*/
private String systemDiskSize;
/**
*
*/
private String systemDickCategory;
/**
* ID
*/
private String regionId;
/**
* ID
*/
private String imageId;
/**
*
*/
private String instanceType;
/**
* ID
*/
private String securityGroupId;
/**
* ID
*/
private String vSwitchId;
/**
*
*/
private String instanceName;
/**
*
*/
private Integer internetMaxBandwidthIn;
/**
*
*/
private Integer internetMaxBandwidthOut;
/**
*
*/
private Boolean uniqueSuffix;
/**
*
*/
private String password;
/**
* ID
*/
private String zoneId;
/**
*
*/
private String internetChargeType;
/**
*
*/
private Integer amount;
/**
*
*/
private Integer minAmount;
/**
*
*/
private String periodUnit;
/**
*
*/
private Integer period;
/**
*
*/
private String instanceChargeType;
/**
* IP
*/
private String privateIpAddress;
}

View File

@ -1,101 +0,0 @@
package com.zhilian.online.domain.req;
import lombok.*;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain.req
* @Author: LiYuan
* @CreateTime: 2024-04-12 15:37
* @Description: openAPI
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class EcsQueryReq {
/**
* ID
*/
@NotBlank
private String regionId;
/**
* ID
*/
private String vpcId;
/**
* ID
*/
private String vSwitchId;
/**
* ID
*/
private String zoneId;
/**
*
* classic
* vpc VPC
*/
private String instanceNetworkType;
/**
* ID
*/
private String securityGroupId;
/**
* ID ["i-bp67acfmxazb4p****", "i-bp67acfmxazb4p****", "i-bp67acfmxazb4p****"]
*/
private List<String> instanceIds;
/**
*
*/
private Integer pageNumber = 1;
/**
*
*/
private Integer pageSize = 10;
/**
* IP ["172.16.1.1", "172.16.2.1", "172.16.10.1"]
*/
private String privateIpAddresses;
/**
* IP ["172.16.1.1", "172.16.2.1", "172.16.10.1"]
*/
private String publicIpAddresses;
/**
* 使*
*/
private String instanceName;
/**
* ID
*/
private String imageId;
/**
*
*/
private String status;
/**
*
*/
private String instanceType;
}

View File

@ -0,0 +1,34 @@
package com.zhilian.online.domain.req;
import lombok.*;
import javax.validation.constraints.NotBlank;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain.req
* @Author: LiYuan
* @CreateTime: 2024-03-31 09:03
* @Description:
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class GatherRegReq {
/**
* ID
*/
@NotBlank
private String clientId;
/**
*
*/
private String token;
}

View File

@ -1,26 +0,0 @@
package com.zhilian.online.load.abs;
import com.zhilian.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.abs
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:09
* @Description:
* @Version: 1.0
*/
public abstract class GatewayCacheAbs<K> {
@Autowired
public RedisService redisService;
public abstract String getPre();
public String encode(K key) {
return getPre() + key;
}
}

View File

@ -1,66 +0,0 @@
package com.zhilian.online.load.cache;
import com.zhilian.common.redis.service.RedisService;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:11
* @Description: 100IP 线
* @Version: 1.0
*/
@Component
public class GatewayLoadNodeCache extends GatewayCacheAbs<String> {
private final static String gatewayLoadNodeKey = "node";
@Override
public String getPre() {
return "gateway:load:";
}
/**
* @description:
* @author: LiYuan
* @param: nodeList
* @return: void
**/
public void put(List<String> nodeList) {
redisService.deleteObject(encode(gatewayLoadNodeKey));
redisService.setCacheList(encode(gatewayLoadNodeKey), nodeList);
}
/**
* @description:
* @author: LiYuan
* @param: null
* @return: List<String>
**/
public List<String> get() {
return redisService.getCacheList(encode(gatewayLoadNodeKey));
}
/**
* @description:
* @author: LiYuan
* @param: index
* @return: String node
**/
public String getByIndex(Long index){
if (null == index || index > 100){
throw new RuntimeException("下标违法,不在[0-100]内");
}
return redisService.getcacheListValue(encode(gatewayLoadNodeKey),index);
}
}

View File

@ -1,71 +0,0 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:34
* @Description:
* @Version: 1.0
*/
@Component
public class GatewayLoadSeriesCache extends GatewayCacheAbs<String> {
private final static String gatewayLoadSeriesKey = "series";
@Override
public String getPre() {
return "gateway:load:";
}
/**
* @description: Bean
* @author: LiYuan
* @param:
* @return:
**/
@PostConstruct
public void init() {
redisService.setCacheObject(encode(gatewayLoadSeriesKey), 0);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return: Long
**/
public Long incrementAndGet() {
return redisService.increment(encode(gatewayLoadSeriesKey), 1L);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public Long get() {
return redisService.getCacheObject(encode(gatewayLoadSeriesKey));
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void reset() {
this.init();
}
}

View File

@ -1,54 +0,0 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import java.util.*;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-19 19:42
* @Description:
* @Version: 1.0
*/
public class GatewayNodeCarsCache extends GatewayCacheAbs<String> {
@Override
public String getPre() {
return "gateway:node:cars";
}
/**
* @description: 线
* @author: LiYuan
* @param: String nodeId, String vin
* @return: void
**/
public void put(String nodeId, String vin) {
redisService.setCacheSet(encode(nodeId), vin);
}
/**
* @description: vin
* @author: LiYuan
* @param: String nodeId
* @return: void
**/
public List<String> get(String nodeId) {
Set<String> res = redisService.getCacheSet(encode(nodeId));
return res.stream().map(String::valueOf).toList();
}
/**
* @description: 线
* @author: LiYuan
* @param: String nodeId, String vin
* @return: void
**/
public void remove(String nodeId, String vin) {
redisService.deleteCacheSetValue(encode(nodeId), vin);
}
}

View File

@ -1,68 +0,0 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.domain.model.GatewayNodeInfo;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:44
* @Description: String key(ID) +
* @Version: 1.0
*/
@Component
public class GatewayNodeInfoCache extends GatewayCacheAbs<String > {
@Override
public String getPre() {
return "gateway:node:info:";
}
/**
* @description:
* @author: LiYuan
* @param: GatewayNodeInfo
* @return:
**/
public void put(GatewayNodeInfo gatewayNodeInfo){
redisService.setCacheObject(encode(gatewayNodeInfo.getNodeId()),gatewayNodeInfo);
}
/**
* @description:
* @author: LiYuan
* @param: nodeId Id
* @return:
**/
public GatewayNodeInfo get(String nodeId){
return redisService.getCacheObject(encode(nodeId));
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public List<GatewayNodeInfo> get(){
return redisService.getCacheObject(encode(getPre()));
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void remove(String nodeId){
redisService.deleteObject(encode(nodeId));
}
}

View File

@ -1,78 +0,0 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.domain.model.GatewayNodeInfo;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 20:03
* @Description:
* @Version: 1.0
*/
@Component
public class GatewayNodeWeightCache extends GatewayCacheAbs<String > {
private final static String gatewayNodeLoadKey = "weight";
@Override
public String getPre() {
return "gateway:node:";
}
/**
* @description: Zset
* @author: LiYuan
* @param: void
* @return: Map<Object,Double>
**/
public Map<Object,Double> get(){
return redisService.getCacheObject(encode(gatewayNodeLoadKey));
}
/**
* @description:
* @author: LiYuan
* @param: gatewayNodeInfo
* @return: score
**/
public Double get(GatewayNodeInfo gatewayNodeInfo){
return redisService.getCacheZsetScore(encode(gatewayNodeLoadKey),gatewayNodeInfo);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void put(GatewayNodeInfo gatewayNodeInfo){
redisService.setCacheZsetValue(encode(gatewayNodeLoadKey),gatewayNodeInfo,0.0);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void increment(GatewayNodeInfo gatewayNodeInfo,Double score){
redisService.incrementScore(encode(gatewayNodeLoadKey),gatewayNodeInfo,score);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void remove(GatewayNodeInfo gatewayNodeInfo) {
redisService.deleteCacheZsetValue(encode(gatewayNodeLoadKey),gatewayNodeInfo);
}
}

View File

@ -1,55 +0,0 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:58
* @Description:
* @Version: 1.0
*/
@Component
public class GatewayVehicleNodeCaChe extends GatewayCacheAbs<String> {
@Override
public String getPre() {
return "gateway:car:";
}
/**
* @description:
* @author: LiYuan
* @param: String vin, String nodeId
* @return:
**/
public void put(String vin, String nodeId) {
redisService.setCacheObject(encode(vin),nodeId);
}
/**
* @description:
* @author: LiYuan
* @param: String vin
* @return:
**/
public void remove(String vin){
redisService.deleteObject(encode(vin));
}
/**
* @description:
* @author: LiYuan
* @param: String vin
* @return:
**/
public String get(String vin){
return redisService.getCacheObject(encode(vin));
}
}

View File

@ -0,0 +1,17 @@
package com.zhilian.online.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 20:48
*/
@Mapper
public interface OnlineGatherMapper{
}

View File

@ -1,6 +1,7 @@
package com.zhilian.online.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zhilian.online.domain.VehicleAccount;
import org.apache.ibatis.annotations.Mapper;
/**
@ -10,7 +11,7 @@ import org.apache.ibatis.annotations.Mapper;
* @date: 2024/3/29 20:45
*/
@Mapper
public interface OnlineLoadCenterMapper{
public interface OnlineLoadCenterMapper extends BaseMapper<VehicleAccount> {

View File

@ -1,7 +1,10 @@
package com.zhilian.online.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.domain.ApifoxModel;
import com.zhilian.online.domain.Gather;
import com.zhilian.online.domain.VehicleAccount;
import com.zhilian.online.domain.req.GatherRegReq;
/**
* @version:
@ -9,7 +12,7 @@ import com.zhilian.online.domain.ApifoxModel;
* @description:
* @date: 2024/3/29 20:42
*/
public interface OnlineLoadCenterService{
public interface OnlineLoadCenterService extends IService<VehicleAccount> {
/**
* @description: ,访
@ -17,7 +20,7 @@ public interface OnlineLoadCenterService{
* @param: vehicle
* @return: Result<OnlineAccount>
**/
Result<String> applyForReg(String clusterId);
Result<String> applyForReg(Gather gather);
/**
* @description: 使
@ -25,7 +28,7 @@ public interface OnlineLoadCenterService{
* @param:
* @return: Result
**/
Result regGather(ApifoxModel apifoxModel);
Result regGather(Gather gather);
/**
@ -34,7 +37,7 @@ public interface OnlineLoadCenterService{
* @param: vin
* @return gather
*/
void applyForConnectToGather(String vin);
Gather applyForConnectToGather(String vin);
/**

View File

@ -0,0 +1,22 @@
package com.zhilian.online.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.mapper.OnlineGatherMapper;
import com.zhilian.online.service.OnlineGatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 20:48
*/
@Service
public class OnlineGatherServiceImpl implements OnlineGatherService {
@Autowired
private OnlineGatherMapper onlineGatherMapper;
}

View File

@ -1,27 +1,23 @@
package com.zhilian.online.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhilian.common.core.domain.Result;
import com.zhilian.common.core.utils.uuid.IdUtils;
import com.zhilian.common.redis.service.RedisService;
import com.zhilian.online.config.RabbitConfig;
import com.zhilian.online.constans.OnlineConstants;
import com.zhilian.online.domain.ApifoxModel;
import com.zhilian.online.domain.EcsInstance;
import com.zhilian.online.domain.model.GatewayNodeInfo;
import com.zhilian.online.load.cache.GatewayNodeInfoCache;
import com.zhilian.online.load.cache.GatewayNodeWeightCache;
import com.zhilian.online.domain.Gather;
import com.zhilian.online.domain.VehicleAccount;
import com.zhilian.online.mapper.OnlineLoadCenterMapper;
import com.zhilian.online.service.OnlineLoadCenterService;
import com.zhilian.online.uitls.AliyunOpenAPIUtils;
import com.zhilian.online.uitls.MqttUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@ -34,7 +30,7 @@ import java.util.stream.Collectors;
*/
@Service
@Slf4j
public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService {
public class OnlineLoadCenterServiceImpl extends ServiceImpl<OnlineLoadCenterMapper, VehicleAccount> implements OnlineLoadCenterService {
/**
*
@ -54,36 +50,20 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private AliyunOpenAPIUtils aliyunOpenAPIUtils;
/**
* MQTT
*/
@Autowired
private MqttUtil mqttUtil;
@Autowired
private GatewayNodeInfoCache gatewayNodeInfoCache;
@Autowired
private GatewayNodeWeightCache gatewayNodeWeightCache;
/**
* @description: , 访
* @description: , 访
* @author: LiYuan
* @param: vehicle
* @return: Result<OnlineAccount>
**/
@Override
public Result<String> applyForReg(String clusterId) {
public Result<String> applyForReg(Gather gather) {
//生成一次性令牌
String token = IdUtils.fastSimpleUUID();
//将令牌信息缓存到Redis中
redisService.setCacheObject(OnlineConstants.NODE_TOKEN_PREFIX + clusterId, token, OnlineConstants.ONLINE_TOKEN_EXPIRE, TimeUnit.SECONDS);
redisService.setCacheObject(OnlineConstants.ONLINE_TOKEN_PREFIX+gather.getClientId(),token, OnlineConstants.ONLINE_TOKEN_EXPIRE, TimeUnit.SECONDS);
//将令牌信息返回客户端
return Result.success(token);
@ -97,59 +77,52 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService {
* @return: Result
**/
@Override
public Result regGather(ApifoxModel apifoxModel) {
public Result regGather(Gather gather) {
//判断登录令牌是否过期,一致
if (!redisService.hasKey(OnlineConstants.NODE_TOKEN_PREFIX + apifoxModel.getClusterId())) {
if (!redisService.hasKey(OnlineConstants.ONLINE_TOKEN_PREFIX + gather.getClientId())) {
return Result.error("令牌已过期");
}
String token = redisService.getCacheObject(OnlineConstants.NODE_TOKEN_PREFIX + apifoxModel.getClusterId());
if (!token.equals(apifoxModel.getToken())) {
String token = redisService.getCacheObject(OnlineConstants.ONLINE_TOKEN_PREFIX + gather.getClientId());
if (!token.equals(gather.getToken())){
return Result.error("令牌错误");
}
GatewayNodeInfo gatewayNodeInfo = generateGatewayNodeInfo(apifoxModel);
//添加节点数据缓存
gatewayNodeInfoCache.put(gatewayNodeInfo);
//为该节点创建Zset负载均衡缓存,将该节点加入List在线节点缓存
gatewayNodeWeightCache.put(gatewayNodeInfo);
//为该节点创建负载均衡缓存
redisService.setCacheZsetValue(OnlineConstants.GATHER_LOAD_CONTROL + gather.getClientId(), JSON.toJSONString(gather), 0.0);
//向RabbitMQ||RocketMQ发送30s延迟消息,确保后续节点上线
rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_NAME, RabbitConfig.DELAY_ROUTING_KEY, JSON.toJSONString(apifoxModel));
rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_NAME, RabbitConfig.DELAY_ROUTING_KEY, JSON.toJSONString(gather));
return Result.success(gatewayNodeInfo,"节点上线");
return Result.success("节点上线");
}
/**
* 线
*
* @return gather
* @author: LiYuan
* @param: vin
* @return gather
*/
@Override
public void applyForConnectToGather(String vin) {
public Gather applyForConnectToGather(String vin) {
//判断车辆是否是我们的车
List<Object> cacheList = redisService.getCacheList("our_car");
List<String> list = cacheList.stream().map(item -> {
return String.valueOf(item);
}).collect(Collectors.toList());
if (!list.contains(vin)) {
if (!list.contains(vin)){
throw new RuntimeException("车辆未登记");
}
//获取负载最少的车辆进行链接
ZSetOperations.TypedTuple cacheZsetMin = redisService.getCacheZsetMin(OnlineConstants.GATHER_LOAD_PREFIX);
ZSetOperations.TypedTuple cacheZsetMin = redisService.getCacheZsetMin(OnlineConstants.GATHER_LOAD_CONTROL);
Gather gather = JSON.parseObject((String) cacheZsetMin.getValue(), Gather.class);
//存放节点车辆信息
redisService.setCacheObject(OnlineConstants.GATHER_LOAD_PREFIX + vin, 1);
redisService.setCacheObject(OnlineConstants.ONLINE_VEHICLE+vin,gather.getClientId());
//发送延迟队列确定车辆上线
rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_FOR_CAR, RabbitConfig.DELAY_ROUTING_FOR_CAR, vin);
rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_FOR_CAR, RabbitConfig.DELAY_ROUTING_FOR_CAR,vin);
return;
return gather;
}
/**
* @description:线
* @author: LiYuan
@ -162,19 +135,4 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService {
}
public GatewayNodeInfo generateGatewayNodeInfo(ApifoxModel apifoxModel) {
EcsInstance ecsInstance = aliyunOpenAPIUtils.queryEcsInstances(new ArrayList<String>() {{
add(apifoxModel.getPrivateIpAddress());
}}).get(0);
return GatewayNodeInfo.builder()
.nodeId(apifoxModel.getClusterId())
.privateIpAddress(ecsInstance.getPrivateIpAddress())
.publicIpAddress(ecsInstance.getPublicIpAddress())
.build();
}
}

View File

@ -1,386 +0,0 @@
package com.zhilian.online.uitls;
import com.aliyun.ecs20140526.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.config.AliyunEcsConfig;
import com.zhilian.online.domain.EcsInstance;
import com.zhilian.online.domain.req.EcsCreateReq;
import com.zhilian.online.domain.req.EcsQueryReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import com.aliyun.ecs20140526.Client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.uitls
* @Author: LiYuan
* @CreateTime: 2024-04-12 14:57
* @Description: OpenApi
* @Version: 1.0
*/
@Component
@Slf4j
public class AliyunOpenAPIUtils {
/**
* ECS
*/
@Autowired
private Client aliyunClient;
@Autowired
private AliyunEcsConfig aliyunEcsConfig;
/**
*
*
* @param: ecsQueryReq
* @return: List<EcsInstance>
*/
public List<EcsInstance> queryEcsInstances(EcsQueryReq ecsQueryReq) {
log.info("开始查询实例{}",ecsQueryReq.getInstanceIds());
List<EcsInstance> ecsInstances = new ArrayList<>();
DescribeInstancesResponse describeInstancesResponse = null;
//将请求参数写入查询请求中
DescribeInstancesRequest describeInstancesRequest = setQueryReq(ecsQueryReq);
RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
describeInstancesResponse = aliyunClient.describeInstancesWithOptions(describeInstancesRequest, runtime);
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
ecsInstances = takeQueryInstances(instances);
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
} catch (Exception aError) {
TeaException error = new TeaException(aError.getMessage(), aError);
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
}
return ecsInstances;
}
/**
*
*
* @param: ecsQueryReq
* @return: List<EcsInstance>
*/
public List<EcsInstance> queryEcsInstancesByPrivateIp(List<String> privateIpAddress) {
log.info("开始查询实例{}",privateIpAddress);
List<EcsInstance> ecsInstances = new ArrayList<>();
DescribeInstancesResponse describeInstancesResponse = null;
//将请求参数写入查询请求中
String ipaddress = parseIpListToString(privateIpAddress);
DescribeInstancesRequest describeInstancesRequest = setQueryReq(ipaddress);
RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
describeInstancesResponse = aliyunClient.describeInstancesWithOptions(describeInstancesRequest, runtime);
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
ecsInstances = takeQueryInstances(instances);
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
} catch (Exception aError) {
TeaException error = new TeaException(aError.getMessage(), aError);
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
}
return ecsInstances;
}
/**
*
*
* @param: instanceIds
* @return: List<EcsInstance>
*/
public List<EcsInstance> queryEcsInstances(List<String> instanceIds) {
log.info("开始查询实例{}",instanceIds);
List<EcsInstance> ecsInstances = new ArrayList<>();
DescribeInstancesResponse describeInstancesResponse = null;
//将请求参数写入查询请求中
DescribeInstancesRequest describeInstancesRequest = setQueryReq(instanceIds);
RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
describeInstancesResponse = aliyunClient.describeInstancesWithOptions(describeInstancesRequest, runtime);
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
ecsInstances = takeQueryInstances(instances);
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
} catch (Exception aError) {
TeaException error = new TeaException(aError.getMessage(), aError);
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
}
return ecsInstances;
}
/**
* @description:
* @author: LiYuan
* @param:
* @return: void
**/
public List<String> createInstance(EcsCreateReq ecsCreateReq) {
//创建实例请求
RunInstancesRequest runInstancesRequest = makeRunInstancesRequest(ecsCreateReq);
RuntimeOptions runtime = new RuntimeOptions();
List<String> instanceIds = new ArrayList<>();
try {
// 复制代码运行请自行打印 API 的返回值
RunInstancesResponse res = aliyunClient.runInstancesWithOptions(runInstancesRequest, runtime);
//打印执行结果
RunInstancesResponseBody body = res.getBody();
instanceIds = body.getInstanceIdSets().getInstanceIdSet();
log.info("执行结果:[{}],请求ID:[{}],创建实例ID:[{}]",
200 == res.getStatusCode() ? "创建成功" : "创建失败",
body.getRequestId(), instanceIds);
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]",
error.getCode(), error.getMessage(), error.getData());
} catch (Exception aError) {
TeaException error = new TeaException(aError.getMessage(), aError);
log.error("code:[{}],message:[{}],data:[{}]",
error.getCode(), error.getMessage(), error.getData());
}
// List<EcsInstance> ecsInstances = queryEcsInstances(instanceIds);
// putNodeOfCreatedCache(ecsInstances);
return instanceIds;
}
public Result deleteInstance(String instanceId) {
Result result = new Result<>();
DeleteInstancesRequest deleteInstancesRequest = new DeleteInstancesRequest()
.setRegionId(aliyunEcsConfig.getRegionId())
.setDryRun(false)
.setForce(true)
.setTerminateSubscription(false)
.setInstanceId(Arrays.asList(instanceId));
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
DeleteInstancesResponse deleteInstancesResponse = aliyunClient.deleteInstancesWithOptions(deleteInstancesRequest, runtime);
Integer statusCode = deleteInstancesResponse.getStatusCode();
DeleteInstancesResponseBody body = deleteInstancesResponse.getBody();
log.info(200 == statusCode ? "删除成功" : "删除失败");
result.setCode(statusCode);
result.setData(body);
result.setMsg(200 == statusCode ? "删除成功" : "删除失败");
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
}
return result;
}
/**
* @description:
* @author: LiYuan
* @param: EcsQueryReq
* @return: DescribeInstancesRequest
**/
public DescribeInstancesRequest setQueryReq(EcsQueryReq ecsQueryReq) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("[");
ecsQueryReq.getInstanceIds().forEach(item ->{
stringBuffer.append("\"" + item + "\",");
});
stringBuffer.deleteCharAt(stringBuffer.length()-1);
stringBuffer.append("]");
return new DescribeInstancesRequest()
.setRegionId(aliyunEcsConfig.getRegionId())
.setInstanceIds(stringBuffer.toString());
// .setInstanceName(ecsQueryReq.getInstanceName())
// .setPageNumber(ecsQueryReq.getPageNumber())
// .setPageSize(ecsQueryReq.getPageSize())
// .setVpcId(ecsQueryReq.getVpcId())
// .setVSwitchId(ecsQueryReq.getVSwitchId())
// .setZoneId(ecsQueryReq.getZoneId())
// .setInstanceNetworkType(ecsQueryReq.getInstanceNetworkType())
// .setSecurityGroupId(ecsQueryReq.getSecurityGroupId())
// .setPrivateIpAddresses(ecsQueryReq.getPrivateIpAddresses())
// .setPublicIpAddresses(ecsQueryReq.getPublicIpAddresses())
// .setInstanceName(ecsQueryReq.getInstanceName())
// .setImageId(ecsQueryReq.getImageId())
// .setInstanceType(ecsQueryReq.getInstanceType())
// .setStatus(ecsQueryReq.getStatus());
}
/**
* @description:
* @author: LiYuan
* @param: EcsQueryReq
* @return: DescribeInstancesRequest
**/
public DescribeInstancesRequest setQueryReq(String ipAddresses) {
return new DescribeInstancesRequest()
.setRegionId(aliyunEcsConfig.getRegionId())
.setPrivateIpAddresses(ipAddresses);
}
public String parseIpListToString(List<String> ipAddress){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("[");
ipAddress.forEach(item ->{
stringBuffer.append("\"" + item + "\",");
});
stringBuffer.deleteCharAt(stringBuffer.length()-1);
stringBuffer.append("]");
return stringBuffer.toString();
}
/**
* @description:
* @author: LiYuan
* @param: EcsQueryReq
* @return: DescribeInstancesRequest
**/
public DescribeInstancesRequest setQueryReq(List<String> instances) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("[");
instances.forEach(item ->{
stringBuffer.append("\"" + item + "\",");
});
stringBuffer.deleteCharAt(stringBuffer.length()-1);
stringBuffer.append("]");
return new DescribeInstancesRequest()
.setRegionId(aliyunEcsConfig.getRegionId())
.setInstanceIds(stringBuffer.toString());
// .setInstanceName(ecsQueryReq.getInstanceName())
// .setPageNumber(ecsQueryReq.getPageNumber())
// .setPageSize(ecsQueryReq.getPageSize())
// .setVpcId(ecsQueryReq.getVpcId())
// .setVSwitchId(ecsQueryReq.getVSwitchId())
// .setZoneId(ecsQueryReq.getZoneId())
// .setInstanceNetworkType(ecsQueryReq.getInstanceNetworkType())
// .setSecurityGroupId(ecsQueryReq.getSecurityGroupId())
// .setPrivateIpAddresses(ecsQueryReq.getPrivateIpAddresses())
// .setPublicIpAddresses(ecsQueryReq.getPublicIpAddresses())
// .setInstanceName(ecsQueryReq.getInstanceName())
// .setImageId(ecsQueryReq.getImageId())
// .setInstanceType(ecsQueryReq.getInstanceType())
// .setStatus(ecsQueryReq.getStatus());
}
/**
* @description:
* @author: LiYuan
* @param: DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances
* @return: List<EcsInstance>
**/
public List<EcsInstance> takeQueryInstances(DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances) {
ArrayList<EcsInstance> ecsInstances = new ArrayList<>();
//遍历请求结果,取出查询到的Ecs实例
instances.getInstance().stream().forEach(item -> {
EcsInstance ecsInstance = EcsInstance.builder()
.instanceId(item.getInstanceId())
.instanceName(item.getInstanceName())
.regionId(aliyunEcsConfig.getRegionId())
.status(item.getStatus())
.instanceType(item.getInstanceType())
.cpu(item.getCpu())
.memory(item.getMemory())
.localStorageCapacity(item.getLocalStorageCapacity())
.osName(item.getOSName())
.instanceNetworkType(item.getInstanceNetworkType())
.internetMaxBandwidthOut(item.getInternetMaxBandwidthOut())
.internetMaxBandwidthIn(item.getInternetMaxBandwidthIn())
.publicIpAddress(item.getPublicIpAddress().getIpAddress())
.privateIpAddress(item.getVpcAttributes().getPrivateIpAddress().getIpAddress())
.vpcId(item.getVpcAttributes().getVpcId())
.securityGroupIds(item.getSecurityGroupIds().getSecurityGroupId())
.creationTime(item.getCreationTime())
.expiredTime(item.getExpiredTime())
.recyclable(item.getRecyclable())
.build();
ecsInstances.add(ecsInstance);
});
return ecsInstances;
}
/**
*
*
* @param: ecsCreateReq
* @return: RunInstancesRequest
*/
public RunInstancesRequest makeRunInstancesRequest(EcsCreateReq ecsCreateReq) {
//构建磁盘配置
RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setSize(ecsCreateReq.getSystemDiskSize())
.setCategory(ecsCreateReq.getSystemDickCategory());
//构建创建实例请求
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
.setRegionId(aliyunEcsConfig.getRegionId())
.setImageId(ecsCreateReq.getImageId())
.setInstanceType(ecsCreateReq.getInstanceType())
.setSecurityGroupId(ecsCreateReq.getSecurityGroupId())
.setVSwitchId(ecsCreateReq.getVSwitchId())
.setInstanceName(ecsCreateReq.getInstanceName())
.setInternetMaxBandwidthIn(ecsCreateReq.getInternetMaxBandwidthIn())
.setInternetMaxBandwidthOut(ecsCreateReq.getInternetMaxBandwidthOut())
.setUniqueSuffix(ecsCreateReq.getUniqueSuffix())
.setPassword(ecsCreateReq.getPassword())
.setZoneId(ecsCreateReq.getZoneId())
.setInternetChargeType(ecsCreateReq.getInternetChargeType())
.setSystemDisk(systemDisk)
.setAmount(ecsCreateReq.getAmount())
.setMinAmount(ecsCreateReq.getMinAmount())
.setPeriodUnit(ecsCreateReq.getPeriodUnit())
.setPeriod(ecsCreateReq.getPeriod())
.setInstanceChargeType(ecsCreateReq.getInstanceChargeType())
.setPrivateIpAddress(ecsCreateReq.getPrivateIpAddress());
return runInstancesRequest;
}
}

View File

@ -1,68 +0,0 @@
package com.zhilian.online.uitls;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhilian.online.constans.OnlineConstants;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.RequestBuilder;
import java.io.IOException;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.uitls
* @Author: LiYuan
* @CreateTime: 2024-04-17 21:41
* @Description: mqtt
* @Version: 1.0
*/
@Component
@Slf4j
public class MqttUtil {
/**
* @description: ipmqttfluxmq
* @author: LiYuan
* @param: ipAddress
* @return: Integer
**/
public Integer getLoadInfoByIp(String ipAddress) {
int num = 0;
String URL = OnlineConstants.HTTP_PREFIX + ipAddress + OnlineConstants.FLUXMQ_INFO_URL;
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder()
.url(URL)
.get()
.addHeader("User-Agent","Apifox/1.0.0(https://apifox.com)")
.addHeader("AccessToken","")
.build();
try {
Response response = client.newCall(build).execute();
JSONArray jsonArray = JSONArray.parseArray(response.body().string());
JSONObject jsonObject = jsonArray.getJSONObject(0);
//获取mqttInfo对象的值
JSONObject mqttInfo = jsonObject.getJSONObject("mqttInfo");
//获取fluxmq链接数
num = mqttInfo.getIntValue("connectSize");
log.info("{}的fluxMq链接数为{}",ipAddress,num);
} catch (IOException e) {
log.error(e.getMessage());
}
return num;
}
}

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhilian.online.mapper.OnlineGatherMapper">
</mapper>