Compare commits

..

5 Commits

Author SHA1 Message Date
玉安君 682dd2f6e0 feat commit
网关负载功能
2024-04-20 09:36:24 +08:00
玉安君 a3059cbbf7 feat commit
网关负载功能
2024-04-19 20:20:36 +08:00
玉安君 3857e3a875 feat commit
网关负载功能
2024-04-18 21:38:49 +08:00
玉安君 4d1cb943ac Merge remote-tracking branch 'origin/master' 2024-04-16 20:39:10 +08:00
玉安君 e6100a1318 feat commit
网关负载功能
2024-04-16 20:38:55 +08:00
40 changed files with 2039 additions and 474 deletions

103
pom.xml
View File

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

View File

@ -156,13 +156,13 @@ public class RedisService {
/** /**
* Set * Set
* *
* @param key * @param key
* @param setValue * @param setValue
* @return * @return
*/ */
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final T setValue) { public <T> BoundSetOperations<String, T> setCacheSet(final String key, final T setValue) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key); BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
setOperation.add(setValue); setOperation.add(setValue);
return setOperation; return setOperation;
} }
@ -272,8 +272,6 @@ public class RedisService {
} }
/** /**
* Zset * Zset
* *
@ -310,6 +308,7 @@ public class RedisService {
/** /**
* *
*
* @param zkey * @param zkey
* @param start * @param start
* @param end * @param end
@ -329,46 +328,50 @@ public class RedisService {
/** /**
* ,delta, * ,delta,
*
* @param zkey * @param zkey
* @param value * @param value
* @param delta * @param delta
* @param <T> * @param <T>
*/ */
public <T> Double incrementScore(final String zkey, final T value, final Double delta){ public <T> Double incrementScore(final String zkey, final T value, final Double delta) {
return redisTemplate.opsForZSet().incrementScore(zkey,value,delta); return redisTemplate.opsForZSet().incrementScore(zkey, value, delta);
} }
/** /**
* *
*
* @param zkey * @param zkey
* @param values * @param values
* @return
* @param <T> * @param <T>
* @return
*/ */
public <T> Long removeCacheZsetBatch(final String zkey,final T... values){ public <T> Long removeCacheZsetBatch(final String zkey, final T... values) {
return redisTemplate.opsForZSet().remove(zkey,values); return redisTemplate.opsForZSet().remove(zkey, values);
} }
/** /**
* , * ,
*
* @param zkey * @param zkey
* @param start * @param start
* @param end * @param end
* @return * @return
*/ */
public Set<Double> reverseRange(final String zkey,final Long start,final Long end){ public Set<Double> reverseRange(final String zkey, final Long start, final Long end) {
return redisTemplate.opsForZSet().reverseRange(zkey,start,end); return redisTemplate.opsForZSet().reverseRange(zkey, start, end);
} }
/** /**
* *
*
* @param zkey * @param zkey
* @param min * @param min
* @param max * @param max
* @return * @return
*/ */
public Set<Double> rangeByScore(final String zkey,final Double min,final Double max){ public Set<Double> rangeByScore(final String zkey, final Double min, final Double max) {
return redisTemplate.opsForZSet().rangeByScore(zkey,min,max); return redisTemplate.opsForZSet().rangeByScore(zkey, min, max);
} }
/** /**
@ -377,7 +380,7 @@ public class RedisService {
* @param zkey * @param zkey
* @return * @return
*/ */
public ZSetOperations.TypedTuple getCacheZsetMin(final String zkey){ public ZSetOperations.TypedTuple getCacheZsetMin(final String zkey) {
ZSetOperations.TypedTuple typedTuple = redisTemplate.opsForZSet().popMin(zkey); ZSetOperations.TypedTuple typedTuple = redisTemplate.opsForZSet().popMin(zkey);
return typedTuple; return typedTuple;
} }
@ -393,13 +396,43 @@ public class RedisService {
return redisTemplate.keys(pattern); return redisTemplate.keys(pattern);
} }
public void deleteCacheSet(String key) { public void deleteCacheSet(final String key) {
SetOperations setOperations = redisTemplate.opsForSet(); SetOperations setOperations = redisTemplate.opsForSet();
setOperations.remove(key); setOperations.remove(key);
} }
public <T> void deleteCacheSetValue(String key, T value) { public <T> void deleteCacheSetValue(final String key, final T value) {
SetOperations setOperations = redisTemplate.opsForSet(); SetOperations setOperations = redisTemplate.opsForSet();
setOperations.remove(key,value); 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);
} }
} }

View File

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

View File

@ -0,0 +1,46 @@
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,11 +4,18 @@ import com.zhilian.common.security.annotation.EnableCustomConfig;
import com.zhilian.common.security.annotation.EnableMyFeignClients; import com.zhilian.common.security.annotation.EnableMyFeignClients;
import com.zhilian.common.swagger.annotation.EnableCustomSwagger2; import com.zhilian.common.swagger.annotation.EnableCustomSwagger2;
import com.zhilian.online.controller.OnlineLoadCenterController; 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.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner; import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import java.util.List;
/** /**
* @version: * @version:
@ -20,9 +27,45 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableCustomSwagger2 @EnableCustomSwagger2
@EnableMyFeignClients @EnableMyFeignClients
@SpringBootApplication @SpringBootApplication
public class ZhiLianOnlineApplication{ @Slf4j
public class ZhiLianOnlineApplication implements ApplicationRunner {
@Autowired
private AliyunOpenAPIUtils aliyunOpenAPIUtils;
public static void main(String[] args) { 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

@ -0,0 +1,70 @@
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() { public void initMqtt() {
log.info("mqttx连接中......"); log.info("mqttx连接中......");

View File

@ -16,7 +16,7 @@ public class OnlineConstants {
/** /**
* *
*/ */
public static final String ONLINE_TOKEN_PREFIX = "online_token:"; public static final String NODE_TOKEN_PREFIX = "node_token:";
/** /**
* *
@ -26,11 +26,26 @@ public class OnlineConstants {
/** /**
* *
*/ */
public static final String GATHER_LOAD_CONTROL = "gather_info_control"; public static final String GATHER_LOAD_PREFIX = "gather:load:";
/** /**
* * 线
*/ */
public static final String ONLINE_VEHICLE = "online_vehicle:"; 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";

View File

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

View File

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

View File

@ -1,49 +0,0 @@
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

@ -0,0 +1,70 @@
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

@ -0,0 +1,30 @@
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

@ -0,0 +1,261 @@
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

@ -0,0 +1,28 @@
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

@ -1,70 +0,0 @@
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

@ -0,0 +1,58 @@
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

@ -0,0 +1,63 @@
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

@ -1,37 +0,0 @@
//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

@ -1,70 +0,0 @@
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

@ -0,0 +1,35 @@
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

@ -0,0 +1,123 @@
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

@ -0,0 +1,101 @@
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

@ -1,34 +0,0 @@
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

@ -0,0 +1,26 @@
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

@ -0,0 +1,66 @@
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

@ -0,0 +1,71 @@
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

@ -0,0 +1,54 @@
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

@ -0,0 +1,68 @@
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

@ -0,0 +1,78 @@
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

@ -0,0 +1,55 @@
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

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

View File

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

View File

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

@ -0,0 +1,386 @@
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

@ -0,0 +1,68 @@
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

@ -1,7 +0,0 @@
<?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>