master
31353 2024-04-18 22:42:22 +08:00
commit 30f4424ac1
34 changed files with 2488 additions and 0 deletions

38
.gitignore vendored 100644
View File

@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

185
pom.xml 100644
View File

@ -0,0 +1,185 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.muyu</groupId>
<artifactId>LoadCenter</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>darabonba-string</artifactId>
<version>0.0.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea</artifactId>
<version>[1.0.3, 2.0.0)</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>ecs20140526</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-openapi</artifactId>
<version>0.3.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-util</artifactId>
<version>0.2.21</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-console</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>darabonba-env</artifactId>
<version>0.1.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.18</version> <!-- 或者其他你希望使用的版本号 -->
<scope>test</scope> <!-- 这是测试依赖,应该放在 test scope 中 -->
</dependency>
<!-- SpringBoot Boot Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.3</version>
<extensions>true</extensions>
<configuration>
<serverId>sonatype-nexus-staging</serverId>
<nexusUrl>https://s01.oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<encoding>UTF-8</encoding>
<doclint>none</doclint>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.aliyun.sample.Sample</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-gpg-plugin</artifactId>-->
<!-- <version>1.6</version>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>sign-artifacts</id>-->
<!-- <phase>verify</phase>-->
<!-- <goals>-->
<!-- <goal>sign</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- <configuration>-->
<!-- <executable>C:\Program Files (x86)\GnuPG\bin\gpg.exe</executable>-->
<!-- </configuration>-->
<!-- </plugin>-->
</plugins>
</build>
</project>

View File

@ -0,0 +1,18 @@
package com.guo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author gxb
* @description
* @date 2024-04-18 11:29
*/
@SpringBootApplication
@EnableScheduling
public class LoadCrenterApplication {
public static void main(String[] args) {
SpringApplication.run(LoadCrenterApplication.class,args);
}
}

View File

@ -0,0 +1,351 @@
package com.guo.aly;
import com.alibaba.fastjson2.JSON;
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.guo.aly.config.AliConfig;
import com.guo.aly.model.EcsSelectModel;
import com.guo.aly.model.EscRemoveModel;
import com.guo.aly.model.InstanceInfo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author gxb
* @description TODO
* @date 2024-04-18 16:15
*/
@Service
@Log4j2
public class ALYunEcsService {
private final AliConfig aliConfig;
private final Client client;
public ALYunEcsService(AliConfig aliConfig, Client client) {
this.aliConfig = aliConfig;
this.client = client;
}
/**
* ID
* @param ecsSelectModel
* @return
*/
public List<InstanceInfo> selectEscList(EcsSelectModel ecsSelectModel){
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
.setRegionId(aliConfig.getRegionId());
if (ecsSelectModel.getInstanceNameList() == null || ecsSelectModel.getInstanceIdList().isEmpty()){
describeInstancesRequest.setInstanceName("*");
}else {
describeInstancesRequest.setInstanceName(Common.toJSONString(ecsSelectModel.getInstanceNameList()));
}
if (ecsSelectModel.getInstanceIdList() != null || !ecsSelectModel.getInstanceIdList().isEmpty()){
describeInstancesRequest.setInstanceIds(Common.toJSONString(ecsSelectModel.getInstanceIdList()).toString());
} else {
describeInstancesRequest.setInstanceName(Common.toJSONString(ecsSelectModel.getInstanceNameList()));
}
describeInstancesRequest.setPageSize(10);
RuntimeOptions runtime = new RuntimeOptions();
//初始化返回值
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instanceList = null;
try {
// 复制代码运行请自行打印 API 的返回值
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
//能返回的值
instanceList = instances.getInstance();
if (instanceList == null || instanceList.isEmpty()) {
return new ArrayList<>();
}
return instanceList.stream()
.map(instance -> {
return InstanceInfo.builder()
.instanceId(instance.getInstanceId())
.instanceName(instance.getInstanceName())
.publicIpAddress(instance.getPublicIpAddress().getIpAddress().toString())
.privateIpAddress(instance.getVpcAttributes().getPrivateIpAddress().ipAddress.toString())
.build();
}).toList();
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
log.error("状态码是:[{}],信息是:[{}],返回的结果是:[{}]", error.getCode(), error.getMessage(), error);
} catch (Exception _error) {
TeaException error = new TeaException();
log.error("code:[{}],信息是:[{}],返回的结果是:[{}]",error.getCode(), error.getMessage(), error);
}
return new ArrayList<>();
}
/**
*
* @throws Exception
*/
public String createAnServers() throws Exception {
// 地域Id
//String regionId = "cn-shanghai";
String regionId = aliConfig.getRegionId();
// 镜像 ID启动实例时选择的镜像资源。
// String imageId = "m-uf6elrscl3c9wk6o762l";
String imageId = aliConfig.getImageId();
// 实例规格
//String instanceType = "ecs.u1-c1m1.large";
String instanceType = aliConfig.getInstanceType();
// 新创建实例所属于的安全组 ID。
//String securityGroupId = "sg-uf6bj6vxp8ruhvffdsau";
String securityGroupId = aliConfig.getSecurityGroupId();
// 虚拟交换机 ID。
//String vSwitchId = "vsw-uf66jtgij0ptqxf1ix6l7 ";
String vSwitchId = aliConfig.getVSwitchId();
// 公网出带宽最大值,单位为 Mbit/s。取值范围0~100。 默认值0。
//Integer internetMaxBandwidthOut = Integer.parseInt("2");
Integer internetMaxBandwidthOut = Integer.parseInt(aliConfig.getInternetMaxBandwidthOut());
// 网络计费类型。取值范围:
// PayByBandwidth: 按固定带宽计费。
// PayByTraffic: 按使用流量计费。
// 默认值PayByTraffic。
//String internetChargeType = "PayByTraffic";
String internetChargeType = aliConfig.getInternetChargeType();
// 系统盘大小
//String size = "20";
String size = aliConfig.getSize();
// 系统盘的云盘种类
//String category = "cloud_essd";
String category = aliConfig.getCategory();
// ECS实例的计费方式
// PrePaid包年包月
// PostPaid按量付费
//String instanceChargeType = "PostPaid";
String instanceChargeType = aliConfig.getInstanceChargeType();
// 批量创建实例
String instances = RunInstances(client, regionId, imageId, instanceType, securityGroupId, vSwitchId, internetMaxBandwidthOut, internetChargeType, size, category, instanceChargeType);
//返回实例ID
return instances;
}
/**
* 2
* RunInstances ECS
* RunInstancesECSDescribeRecommendInstanceTypeECS
*/
public String RunInstances(Client client, String regionId, String imageId, String instanceType, String securityGroupId, String vSwitchId, Integer internetMaxBandwidthOut, String internetChargeType, String size, String category, String instanceChargeType) throws Exception {
System.setOut(new java.io.PrintStream(System.out, true, "UTF-8"));
RunInstancesRequest request1 = new RunInstancesRequest()
.setRegionId(regionId)
.setImageId(imageId)
.setInstanceType(instanceType)
.setSecurityGroupId(securityGroupId)
.setVSwitchId(vSwitchId)
.setInstanceName("Myname")
.setDescription("Myprocure")
.setInternetMaxBandwidthOut(internetMaxBandwidthOut)
.setInternetChargeType(internetChargeType)
.setInstanceChargeType(instanceChargeType)
// 批量创建五台ECS实例如果不设置该参数默认创建一台ECS实例。
.setAmount(2)
// 如果缺少库存可以接受的最低创建数量。
// minAmount = 2,
// 打开预检参数功能不会实际创建ECS实例只检查参数正确性、用户权限或者ECS库存等问题。
// 实际情况下设置了DryRun参数后Amount必须为1MinAmount必须为空您可以根据实际需求修改代码。
.setDryRun(false)
.setSystemDisk(new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setSize(size)
.setCategory(category));
RunInstancesResponse responces = client.runInstances(request1);
try {
log.info("--------------------批量创建实例开始--------------------");
log.info("--------------------创建实例成功实例ID:" + JSON.toJSONString(responces.body.instanceIdSets.instanceIdSet) + "--------------------");
} catch (TeaException error) {
log.error("--------------------创建实例失败:" + error+ "--------------------");
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
log.error("--------------------创建实例失败:" +error + "--------------------");
}
return JSON.toJSONString(responces.body.instanceIdSets.instanceIdSet);
}
/**
* 1
* @param
* @throws Exception
*/
public String createAnServer() throws Exception {
// 地域Id
//String regionId = "cn-shanghai";
String regionId = aliConfig.getRegionId();
// 镜像 ID启动实例时选择的镜像资源。
// String imageId = "m-uf6elrscl3c9wk6o762l";
String imageId = aliConfig.getImageId();
// 实例规格
//String instanceType = "ecs.u1-c1m1.large";
String instanceType = aliConfig.getInstanceType();
// 新创建实例所属于的安全组 ID。
//String securityGroupId = "sg-uf6bj6vxp8ruhvffdsau";
String securityGroupId = aliConfig.getSecurityGroupId();
// 虚拟交换机 ID。
//String vSwitchId = "vsw-uf66jtgij0ptqxf1ix6l7 ";
String vSwitchId = aliConfig.getVSwitchId();
// 公网出带宽最大值,单位为 Mbit/s。取值范围0~100。 默认值0。
//Integer internetMaxBandwidthOut = Integer.parseInt("2");
Integer internetMaxBandwidthOut = Integer.parseInt(aliConfig.getInternetMaxBandwidthOut());
// 网络计费类型。取值范围:
// PayByBandwidth: 按固定带宽计费。
// PayByTraffic: 按使用流量计费。
// 默认值PayByTraffic。
//String internetChargeType = "PayByTraffic";
String internetChargeType = aliConfig.getInternetChargeType();
// 系统盘大小
//String size = "20";
String size = aliConfig.getSize();
// 系统盘的云盘种类
//String category = "cloud_essd";
String category = aliConfig.getCategory();
// ECS实例的计费方式
// PrePaid包年包月
// PostPaid按量付费
//String instanceChargeType = "PostPaid";
String instanceChargeType = aliConfig.getInstanceChargeType();
// 批量创建实例
String instances = RunInstance(client, regionId, imageId, instanceType, securityGroupId, vSwitchId, internetMaxBandwidthOut, internetChargeType, size, category, instanceChargeType);
return instances;
}
/**
* 1
* RunInstances ECS
* RunInstancesECSDescribeRecommendInstanceTypeECS
*/
public String RunInstance(Client client, String regionId, String imageId, String instanceType, String securityGroupId, String vSwitchId, Integer internetMaxBandwidthOut, String internetChargeType, String size, String category, String instanceChargeType) throws Exception {
System.setOut(new java.io.PrintStream(System.out, true, "UTF-8"));
RunInstancesRequest request1 = new RunInstancesRequest()
.setRegionId(regionId)
.setImageId(imageId)
.setInstanceType(instanceType)
.setSecurityGroupId(securityGroupId)
.setVSwitchId(vSwitchId)
.setInstanceName("Myname")
.setDescription("Myprocure")
.setInternetMaxBandwidthOut(internetMaxBandwidthOut)
.setInternetChargeType(internetChargeType)
.setInstanceChargeType(instanceChargeType)
// 批量创建五台ECS实例如果不设置该参数默认创建一台ECS实例。
//.setAmount(2)
// 如果缺少库存可以接受的最低创建数量。
// minAmount = 2,
// 打开预检参数功能不会实际创建ECS实例只检查参数正确性、用户权限或者ECS库存等问题。
// 实际情况下设置了DryRun参数后Amount必须为1MinAmount必须为空您可以根据实际需求修改代码。
.setDryRun(false)
.setSystemDisk(new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setSize(size)
.setCategory(category));
RunInstancesResponse responces = client.runInstances(request1);
try {
log.info("--------------------批量创建实例开始--------------------");
log.info("--------------------创建实例成功实例ID:" + JSON.toJSONString(responces.body.instanceIdSets.instanceIdSet) + "--------------------");
} catch (TeaException error) {
log.error("--------------------创建实例失败:" + error+ "--------------------");
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
log.error("--------------------创建实例失败:" +error + "--------------------");
}
return JSON.toJSONString(responces.body.instanceIdSets.instanceIdSet);
}
public DescribeInstancesResponse DescribeInstances(Client client, String regionId, String instanceIds, String instanceName) throws Exception {
DescribeInstancesRequest req = new DescribeInstancesRequest()
.setRegionId(regionId)
.setInstanceName(instanceName);
if (!com.aliyun.teautil.Common.empty(instanceIds)) {
req.instanceIds = JSON.toJSONString(com.aliyun.darabonbastring.Client.split(instanceIds, ",", 50));
}
DescribeInstancesResponse resp = client.describeInstances(req);
log.error("--------------------查询需要删除的实例--------------------");
return resp;
}
public void ModifyInstanceAttribute(Client client, String instatnceId) throws Exception {
ModifyInstanceAttributeRequest req = new ModifyInstanceAttributeRequest()
.setInstanceId(instatnceId)
.setDeletionProtection(false);
client.modifyInstanceAttribute(req);
log.info("--------------------" + instatnceId + "释放保护取消成功--------------------");
}
public void DeleteInstances(Client client, String regionId, String instanceIds, String force) throws Exception {
DeleteInstancesRequest req = new DeleteInstancesRequest()
.setRegionId(regionId)
.setInstanceId(com.aliyun.darabonbastring.Client.split(instanceIds, ",", 50))
.setForce(com.aliyun.teautil.Common.equalString(force, "true"));
DeleteInstancesResponse resp = client.deleteInstances(req);
log.info("--------------------实例释放成功--------------------");
log.info(JSON.toJSONString(com.aliyun.teautil.Common.toMap(resp)));
}
/**
*
* @param
* @throws Exception
*/
public void DeleServerCreateAn(EscRemoveModel escRemoveModel) throws Exception {
// 区域ID
//String regionId = "cn-shanghai";
String regionId = aliConfig.getRegionId();
// 多个实例ID用英文逗号分隔
//String instanceIds = "i-uf6h4s0jtpvobykd7vzc";
String instanceIds = escRemoveModel.getInstanceIds();
// 实例名称,支持使用通配符*进行模糊搜索
//String instanceName = "MyFirstEcsInstance";
String instanceName = escRemoveModel.getInstanceName();
// 强制删除有删除保护的机器
//String deleteProtected = "true";
String deleteProtected = "true";
// 强制删除运行中的机器
//String force = "true";
String force = "true";
if (com.aliyun.teautil.Common.equalString(deleteProtected, force)) {
DescribeInstancesResponse describeInstancesResp = DescribeInstances(client, regionId, instanceIds, instanceName);
instanceIds = "";
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : describeInstancesResp.body.instances.instance) {
instanceIds = "" + instance.instanceId + "," + instanceIds + "";
if (instance.deletionProtection) {
ModifyInstanceAttribute(client, instance.instanceId);
}
}
instanceIds = com.aliyun.darabonbastring.Client.subString(instanceIds, 0, -1);
}
if (com.aliyun.teautil.Common.empty(instanceIds)) {
log.info("--------------------无有效实例可删除--------------------");
return ;
}
DeleteInstances(client, regionId, instanceIds, force);
}
}

View File

@ -0,0 +1,87 @@
package com.guo.aly.config;
import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author gxb
* @description TODO
* @date 2024-04-18 16:16
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyun")
public class AliConfig {
private String accessKeyId;
private String accessKeySecret;
/**
* ID
*/
private String regionId;
/**
* ID
*/
private String imageId;
/**
*
*/
private String instanceType;
/**
* ID
*/
private String securityGroupId;
/**
* ID
*/
private String vSwitchId;
/**
* Mbit/s0~100 0
*/
private String internetMaxBandwidthOut;
/**
*
*/
private String internetChargeType;
/**
*
*/
private String size;
/**
*
*/
private String category;
/**
* ECS
*/
private String instanceChargeType;
@Bean
public Client createClient(AliConfig aliConfig) throws Exception {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
// 建议使用更安全的 STS 方式更多鉴权访问方式请参见https://help.aliyun.com/document_detail/378657.html。
Config config = new Config()
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
.setAccessKeyId(aliConfig.getAccessKeyId())
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
.setAccessKeySecret(aliConfig.accessKeySecret)
.setRegionId(aliConfig.getRegionId());
return new Client(config);
}
}

View File

@ -0,0 +1,30 @@
package com.guo.aly.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author gxb
* @description Esc
* @date 2024-04-18 16:24
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EcsSelectModel {
/**
* ID
*/
private List<String> instanceIdList;
/**
*
*/
private List<String> instanceNameList;
}

View File

@ -0,0 +1,28 @@
package com.guo.aly.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author gxb
* @description
* @date 2024-04-18 18:28
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EscRemoveModel {
/**
* ID
*/
private String instanceIds;
/**
*
*/
private String instanceName;
}

View File

@ -0,0 +1,37 @@
package com.guo.aly.model;
import lombok.*;
/**
* @author gxb
* @description
* @date 2024-04-18 16:44
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class InstanceInfo {
/**
* ID
*/
private String instanceId;
/**
*
*/
private String instanceName;
/**
* IP
*/
private String publicIpAddress;
/**
* IP
*/
private String privateIpAddress;
}

View File

@ -0,0 +1,112 @@
package com.guo.common.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
*
*
* @author muyu
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
/**
*
*/
public static final int SUCCESS = 200;
/**
*
*/
public static final int FAIL = 500;
/**
*
*/
public static final int WARN = 501;
private static final long serialVersionUID = 1L;
private int code;
private String msg;
private T data;
public static <T> Result<T> buildCode(int code, String msg, T data){
return restResult(data, code, msg);
}
public static <T> Result<T> success () {
return restResult(null, SUCCESS, null);
}
public static <T> Result<T> success (T data) {
return restResult(data, SUCCESS, null);
}
public static <T> Result<T> success (T data, String msg) {
return restResult(data, SUCCESS, msg);
}
public static <T> Result<T> error () {
return restResult(null, FAIL, null);
}
public static <T> Result<T> error (String msg) {
return restResult(null, FAIL, msg);
}
public static <T> Result<T> error (T data) {
return restResult(data, FAIL, null);
}
public static <T> Result<T> error (T data, String msg) {
return restResult(data, FAIL, msg);
}
public static <T> Result<T> error (int code, String msg) {
return restResult(null, code, msg);
}
public static <T> Result<T> warn () {
return restResult(null, WARN, null);
}
public static <T> Result<T> warn (String msg) {
return restResult(null, WARN, msg);
}
public static <T> Result<T> warn (T data) {
return restResult(data, WARN, null);
}
public static <T> Result<T> warn (T data, String msg) {
return restResult(data, WARN, msg);
}
public static <T> Result<T> warn (int code, String msg) {
return restResult(null, code, msg);
}
private static <T> Result<T> restResult (T data, int code, String msg) {
return Result.<T>builder()
.code(code)
.data(data)
.msg(msg)
.build();
}
public static <T> Boolean isError (Result<T> ret) {
return !isSuccess(ret);
}
public static <T> Boolean isSuccess (Result<T> ret) {
return Result.SUCCESS == ret.getCode();
}
}

View File

@ -0,0 +1,30 @@
package com.guo.common.model;
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,30 @@
package com.guo.common.model;
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,58 @@
package com.guo.common.model;
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,62 @@
package com.guo.common.model;// 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,28 @@
package com.guo.common.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author gxb
* @description
* @date 2024-04-18 19:54
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TotalNumber {
/**
*
*/
private Long nodeNumber;
/**
*
*/
private Long ConnectionTotal;
}

View File

@ -0,0 +1,51 @@
package com.guo.common.redis.configure;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* Redis使FastJson
*
* @author muyu
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
public static final String[] JSON_WHITELIST_STR = {"org.springframework", "com.muyu"};
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(JSON_WHITELIST_STR);
private Class<T> clazz;
public FastJson2JsonRedisSerializer (Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize (T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize (byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER);
}
}

View File

@ -0,0 +1,41 @@
package com.guo.common.redis.configure;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis
*
* @author muyu
*/
@Configuration
@EnableCaching
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public RedisTemplate<Object, Object> redisTemplate (RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}

View File

@ -0,0 +1,386 @@
package com.guo.common.redis.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* spring redis
*
* @author muyu
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisService {
@Autowired
public RedisTemplate redisTemplate;
/**
* IntegerString
*
* @param key
* @param value
*/
public <T> void setCacheObject (final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
public SetOperations opsForSet() {
return redisTemplate.opsForSet();
}
public <K, HK, HV> HashOperations<K, HK, HV> opsForHash() {
return (HashOperations<K, HK, HV>) redisTemplate.opsForHash();
}
// 获取缓存集合的方法,返回 List<String>
public List<String> getCacheSets(String key) {
// 获取绑定的 Set 操作对象
BoundSetOperations<String, ?> setOperation = redisTemplate.boundSetOps(key);
// 获取 Redis 集合中的所有元素,并转换为 List<String>
Set<?> members = setOperation.members();
return members.stream()
.map(Object::toString)
.collect(Collectors.toList());
}
/**
* list
*
* @param key
*
* @return
*/
public <T> List<T> getCacheList (final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
public <T> T getCacheListValue (final String key, long index) {
return (T) redisTemplate.opsForList().index(key, index);
}
/**
*
* @param key
* @param number
* @return
*/
public Long increment(final String key , Long number){
return redisTemplate.opsForValue().increment(key,number);
}
/**
* Redis
* @param key Redis key
* @param value
* @return true false
*/
public boolean addToSet(String key, String value) {
Long added = redisTemplate.opsForSet().add(key, value);
return added == 1?true:false;
}
public ZSetOperations<String, String> opsForZSet() {
return redisTemplate.opsForZSet();
}
/**
* IntegerString
*
* @param key
* @param value
* @param timeout
* @param timeUnit
*/
public <T> void setCacheObject (final String key, final T value, final Long timeout, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
*
*
* @param key Redis
* @param timeout
*
* @return true=false=
*/
public boolean expire (final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
public ValueOperations<String, String> opsForValue() {
return redisTemplate.opsForValue();
}
/**
*
*
* @param key Redis
* @param timeout
* @param unit
*
* @return true=false=
*/
public boolean expire (final String key, final long timeout, final TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
*
*
* @param key Redis
*
* @return
*/
public long getExpire (final String key) {
return redisTemplate.getExpire(key);
}
/**
* key
*
* @param key
*
* @return true false
*/
public Boolean hasKey (String key) {
return redisTemplate.hasKey(key);
}
// 自定义的 expire 方法,支持以小时为单位设置过期时间
public boolean expire(String key, Object value, TimeUnit timeUnit, long duration) {
// 将超时时间转换为小时
long timeoutHours = timeUnit.toHours(duration);
// 检查转换后的小时超时时间是否为正数
if (timeoutHours > 0) {
// 使用 RedisTemplate 设置键的过期时间(单位为秒,需要将小时转换为秒)
return redisTemplate.expire(key, timeoutHours, TimeUnit.HOURS);
} else {
// 如果转换后的超时时间小于等于 0则不设置过期时间返回 false
return false;
}
}
/**
*
*
* @param key
*
* @return
*/
public <T> T getCacheObject (final String key) {
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
*
*
* @param key
*/
public boolean deleteObject (final String key) {
return redisTemplate.delete(key);
}
/**
*
*
* @param collection
*
* @return
*/
public boolean deleteObject (final Collection collection) {
return redisTemplate.delete(collection) > 0;
}
/**
* List
*
* @param key
* @param dataList List
*
* @return
*/
public <T> long setCacheList (final String key, final List<T> dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* list
*
* @param key
*
* @return
*/
public <T> T getCacheList (final String key,Long index) {
return (T) redisTemplate.opsForList().index(key, index);
}
/**
* list
*
* @param key
*
* @return
*/
public <T> List<T> getCacheLists(final String key) {
return (List<T>) redisTemplate.opsForList().range(key, 0, -1);
}
/**
* Set
*
* @param key
* @param dataSet
*
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet (final String key, final Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
setOperation.add(it.next());
}
return setOperation;
}
// 修改后的 setCacheSet 方法,支持设置集合数据和过期时间
public <T> BoundSetOperations<String, T> setCacheSetEndTime(final String key, final Set<T> dataSet, TimeUnit timeUnit, long duration) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext()) {
setOperation.add(it.next());
}
// 设置键的过期时间
setOperation.expire(duration, timeUnit);
return setOperation;
}
/**
* Set
*
* @param key
* @param setValue
*
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSets (final String key, final T setValue) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
setOperation.add(setValue);
return setOperation;
}
/**
* set
*
* @param key
* @param setValue
*
* @return
*/
public <T> void deleteCachSet(String key, String setValue) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
setOperation.remove(setValue);
}
/**
* set
*
* @param key
*
* @return
*/
public <T> Set<T> getCacheSet (final String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap (final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* Map
*
* @param key
*
* @return
*/
public <T> Map<String, T> getCacheMap (final String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
* @param value
*/
public <T> void setCacheMapValue (final String key, final String hKey, final T value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
*
* @return Hash
*/
public <T> T getCacheMapValue (final String key, final String hKey) {
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* Hash
*
* @param key Redis
* @param hKeys Hash
*
* @return Hash
*/
public <T> List<T> getMultiCacheMapValue (final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* Hash
*
* @param key Redis
* @param hKey Hash
*
* @return
*/
public boolean deleteCacheMapValue (final String key, final String hKey) {
return redisTemplate.opsForHash().delete(key, hKey) > 0;
}
/**
*
*
* @param pattern
*
* @return
*/
public Collection<String> keys (final String pattern) {
return redisTemplate.keys(pattern);
}
public void rightPush(String key, String value) {
redisTemplate.opsForList().rightPush(key, value);
}
public Object leftPopAndRemove(String key) {
return redisTemplate.opsForList().leftPop(key);
}
}

View File

@ -0,0 +1,31 @@
package com.guo.controller;
import com.guo.common.domain.Result;
import com.guo.service.impl.GateWayLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author gxb
* @description
* @date 2024-04-18 14:29
*/
@RestController
@RequestMapping("/gateway")
public class GateWayController {
@Autowired
private GateWayLoadService gateWayLoadService;
/**
*
* @return
*/
@GetMapping("/load/node")
public Result<String> loadNode(){
return Result.success(gateWayLoadService.loadNode());
}
}

View File

@ -0,0 +1,53 @@
package com.guo.gateway.cache;
import com.guo.gateway.cache.abs.CacheAbs;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author gxb
* @description
* @date 2024-04-18 11:59
*/
@Component
public class LoadNodeCache extends CacheAbs<String> {
private final static String gatewayLoadNodeKey = "node";
@Override
public String getPre() {
return "gateway:load:";
}
/**
*
* @param nodeList
*/
public void put(List<String> nodeList){
//删除key
redisService.deleteObject(encode(gatewayLoadNodeKey));
//存入节点权重集合
redisService.setCacheList(encode(gatewayLoadNodeKey),nodeList);
}
/**
*
* @return
*/
public List<String> get(){
return redisService.getCacheList(encode(gatewayLoadNodeKey));
}
/**
*
* @param index
* @return
*/
public String getFindByIndex(Long index){
if (index == null || index > 100){
throw new RuntimeException("下标违法【0 - 100】");
}
return redisService.getCacheListValue(encode(gatewayLoadNodeKey),index);
}
}

View File

@ -0,0 +1,51 @@
package com.guo.gateway.cache;
import com.guo.gateway.cache.abs.CacheAbs;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @author gxb
* @description
* @date 2024-04-18 14:15
*/
@Component
public class LoadSeriesCache extends CacheAbs<String> {
private final static String gatewayLoadSeriesKey = "series";
@Override
public String getPre() {
return "gateway:load:";
}
/**
* bean
*/
@PostConstruct
public void init(){
redisService.setCacheObject(encode(gatewayLoadSeriesKey),0L);
}
/**
*
* @return
*/
public Long get(){
return redisService.getCacheObject(encode(gatewayLoadSeriesKey));
}
/**
*
* @return
*/
public Long incrementAndGet(){
return redisService.increment(encode(gatewayLoadSeriesKey),1L);
}
/**
*
*/
public void reset(){ this.init(); }
}

View File

@ -0,0 +1,44 @@
package com.guo.gateway.cache;
import com.guo.gateway.cache.abs.CacheAbs;
import com.guo.gateway.model.NodeInfo;
import org.springframework.stereotype.Component;
/**
* @author gxb
* @description
* @date 2024-04-18 11:43
*/
@Component
public class NodeCache extends CacheAbs<String> {
@Override
public String getPre() {
return "gateway:node:info:";
}
/**
*
* @param nodeInfo
*/
public void put(NodeInfo nodeInfo){
redisService.setCacheObject(encode(nodeInfo.getNodeId()),nodeInfo);
}
/**
*
* @param nodeId ID
* @return
*/
public NodeInfo get(String nodeId){
return redisService.getCacheObject(encode(nodeId));
}
/**
*
* @param nodeId
*/
public void remove(String nodeId){
redisService.deleteObject(encode(nodeId));
}
}

View File

@ -0,0 +1,68 @@
package com.guo.gateway.cache;
import com.guo.gateway.cache.abs.CacheAbs;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author gxb
* @description ID
* @date 2024-04-18 21:17
*/
@Component
public class NodeReduced extends CacheAbs<String> {
private final static int Expiratiotime = 50;
@Override
public String getPre() {
return "reduced:cache:";
}
/**
* ID
* @param nodeId ID
*/
public void put(String nodeId){
Set<String> thresholeSet = new HashSet<>();
thresholeSet.add(nodeId);
redisService.setCacheSetEndTime(encode(nodeId),thresholeSet, TimeUnit.MINUTES,Expiratiotime);
}
/**
*
* @param nodeId ID
* @return true/false
*/
public boolean isWhether(String nodeId){
return redisService.hasKey(encode(nodeId));
}
/**
* ID
*/
public void remove(String nodeId){
redisService.deleteObject(encode(nodeId));
}
/**
* ID
* @return
*/
public List<String> get(String nodeId){
return redisService.getCacheSets(encode(nodeId));
}
/**
*
* @param nodeId ID
* @return
*/
public Long remainingTime(String nodeId){
return redisService.getExpire(encode(nodeId));
}
}

View File

@ -0,0 +1,41 @@
package com.guo.gateway.cache;
import com.guo.gateway.cache.abs.CacheAbs;
import com.guo.gateway.model.NodeJoin;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author gxb
* @description
* @date 2024-04-18 14:27
*/
@Component
public class NodeScoreCache extends CacheAbs<String> {
private final static String gatewayNodeScoreCache = "score";
@Override
public String getPre() {
return "gateway:join:";
}
/**
* ID
* @param nodeJoin
*/
public void save(NodeJoin nodeJoin){
redisService.setCacheSets(encode(gatewayNodeScoreCache),nodeJoin);
}
/**
*
* @return
*/
public List<String> get(){
return redisService.getCacheObject(encode(gatewayNodeScoreCache));
}
}

View File

@ -0,0 +1,44 @@
package com.guo.gateway.cache;
import com.guo.gateway.cache.abs.CacheAbs;
import com.guo.gateway.model.NodeVehicle;
import org.springframework.stereotype.Component;
/**
* @author gxb
* @description VIN
* @date 2024-04-18 14:27
*/
@Component
public class NodeSetVinCache extends CacheAbs<String> {
@Override
public String getPre() {
return "gateway:vehicle:";
}
/**
*
* @param nodeVehicle
*/
public void put(NodeVehicle nodeVehicle){
redisService.setCacheObject(encode(nodeVehicle.getVehicleVin()),nodeVehicle);
}
/**
* ID
* @param vehicleVin VIN
* @return ID
*/
public String get(String vehicleVin){
return redisService.getCacheObject(encode(vehicleVin));
}
/**
*
* @param vehicleVin VIN
*/
public void delete(String vehicleVin){
redisService.deleteObject(encode(vehicleVin));
}
}

View File

@ -0,0 +1,55 @@
package com.guo.gateway.cache;
import com.alibaba.fastjson2.JSON;
import com.guo.gateway.cache.abs.CacheAbs;
import com.guo.gateway.model.NodeVehicle;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author gxb
* @description
* @date 2024-04-18 14:28
*/
@Component
public class VehicleLineNodeCache extends CacheAbs<String> {
@Override
public String getPre() {
return "gateway:vehicleLine:";
}
/**
*VIN ID
* @param nodeVehicle VIN ID
*/
public void save(NodeVehicle nodeVehicle){
String key = encode(nodeVehicle.getNodeId());
String vehicleVin = nodeVehicle.getVehicleVin();
// Collections.singleton(vehicleVin) 来创建一个只包含一个元素 vehicleVin 的集合
redisService.setCacheSet(key, Collections.singleton(vehicleVin));
}
/**
* VIN
* @param nodeId ID
* @return VINSet
*/
public Set<String> get(String nodeId){
return redisService.getCacheSet(encode(nodeId));
}
/**
*
* @param nodeId ID
*/
public void remove(String nodeId){
redisService.deleteObject(encode(nodeId));
}
}

View File

@ -0,0 +1,21 @@
package com.guo.gateway.cache.abs;
import com.guo.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author gxb
* @description
* @date 2024-04-18 11:56
*/
public abstract class CacheAbs<K> {
@Autowired
public RedisService redisService;
public abstract String getPre();
public String encode(K key){
return getPre() + key ;
}
}

View File

@ -0,0 +1,34 @@
package com.guo.gateway.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author gxb
* @description
* @date 2024-04-18 11:40
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NodeInfo {
/**
*
* ID
*/
private String nodeId;
/**
* IP
*/
private String publicIdAddress;
/**
* IP
*/
private String privateIdAddress;
}

View File

@ -0,0 +1,28 @@
package com.guo.gateway.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author gxb
* @description
* @date 2024-04-18 14:48
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NodeJoin {
/**
* ID
*/
private String nodeId;
/**
*
*/
private Long linkingNumber;
}

View File

@ -0,0 +1,28 @@
package com.guo.gateway.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author gxb
* @description
* @date 2024-04-18 15:16
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NodeVehicle {
/**
* VIN
*/
private String vehicleVin;
/**
* ID
*/
private String nodeId;
}

View File

@ -0,0 +1,16 @@
package com.guo.service.impl;
/**
* @author gxb
* @description
* @date 2024-04-18 14:30
*/
public interface GateWayLoadService {
/**
*
* @return
*/
String loadNode();
}

View File

@ -0,0 +1,66 @@
package com.guo.service.impl;
import com.guo.gateway.cache.*;
import com.guo.gateway.model.NodeInfo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
/**
* @author gxb
* @description
* @date 2024-04-18 14:30
*/
@Service
@AllArgsConstructor
public class GateWayLoadServicelmpl implements GateWayLoadService{
/**
*
*/
private final Long nodeLength = 100L;
/**
*
*/
private final LoadNodeCache loadNodeCache;
/**
*
*/
private final LoadSeriesCache loadSeriesCache;
/**
*
*/
private final NodeCache nodeCache;
/**
*
*/
private final NodeScoreCache nodeScoreCache;
/**
* VIN
*/
private final NodeSetVinCache nodeSetVinCache;
/**
*
*/
private final VehicleLineNodeCache vehicleLineNodeCache;
/**
*
* @return
*/
@Override
public String loadNode() {
Long seriesLoad = loadSeriesCache.incrementAndGet(); //获取自增序列值
Long seriesLoadIndex = seriesLoad % nodeLength; //获取负载下标
String loadNodeId = loadNodeCache.getFindByIndex(seriesLoadIndex); //通过获取节点ID
NodeInfo nodeInfo = nodeCache.get(loadNodeId); //获取缓存内节点的公网/内网信息
return nodeInfo.getPublicIdAddress(); //返回公网IP
}
}

View File

@ -0,0 +1,180 @@
package com.guo.task;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.guo.aly.ALYunEcsService;
import com.guo.aly.model.EcsSelectModel;
import com.guo.aly.model.InstanceInfo;
import com.guo.common.model.TotalNumber;
import com.guo.gateway.cache.*;
import com.guo.gateway.model.NodeInfo;
import com.guo.gateway.model.NodeJoin;
import com.guo.task.Contraction.ContractionVolume;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
* @author gxb
* @description
* @date 2024-04-18 19:01
*/
@Component
@Log4j2
@AllArgsConstructor
public class Collection {
/**
*
*/
private final Long nodeLength = 100L;
/**
*
*/
private final LoadNodeCache loadNodeCache;
/**
*
*/
private final LoadSeriesCache loadSeriesCache;
/**
* ip
*/
private final NodeCache nodeCache;
/**
*
*/
private final NodeScoreCache nodeScoreCache;
/**
* VIN
*/
private final NodeSetVinCache nodeSetVinCache;
/**
*
*/
private final VehicleLineNodeCache vehicleLineNodeCache;
/**
*
*/
private final NodeReduced nodeReduced;
/**
*
*/
@Autowired
private ContractionVolume contractionVolume;
@Autowired
private ALYunEcsService alYunEcsService;
@Scheduled(cron = "0/10 * * * * ?")
public void scheduledEcsCompanding() {
//查询阿里云是否存在实例
EcsSelectModel ecsSelectModel = new EcsSelectModel();
ecsSelectModel.setInstanceNameList(Arrays.asList("Myname"));
//实例集合
List<InstanceInfo> instanceLists = alYunEcsService.selectEscList(ecsSelectModel);
//节点计数
Long nodeNumber = 0L;
//所有节点连接数总数
long connectionTotal = 0L;
//判断实例集合是否为空
if (!instanceLists.isEmpty()){
//将实例存入缓存
for (InstanceInfo instance : instanceLists) {
//清空 缓存中节点信息
nodeCache.remove(instance.getInstanceId());
// 创建一个新的 NodeInfo 对象
NodeInfo nodeInfo = new NodeInfo();
// 设置实例的信息
nodeInfo.setNodeId(instance.getInstanceId());
nodeInfo.setPublicIdAddress(instance.getPublicIpAddress());
nodeInfo.setPrivateIdAddress(instance.getPrivateIpAddress());
// 将新的 NodeInfo 对象放入缓存
nodeCache.put(nodeInfo);
//获取每个FluxMQ运行信息
String URL = "http://" + instance.getPublicIpAddress()+":8080/public/cluster";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.get()
.addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
.addHeader("Accesstoken", "")
.build();
try {
Response response = client.newCall(request).execute();
JSONArray jsonArray = JSONArray.parseArray(response.body().string());
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject mqttInfo = jsonObject.getJSONObject("mqttInfo");
int connectSize = mqttInfo.getIntValue("connectSize");
log.info("当前:" + instance.getInstanceId() + ",的连接数:" + connectSize);
//计数
nodeNumber++;
connectionTotal+=connectSize;
//将连接数存入缓存
// key网关负载业务 value:网关节点ID + 连接数
NodeJoin nodeJoin = new NodeJoin();
nodeJoin.setNodeId(instance.getInstanceId());
nodeJoin.setLinkingNumber(Long.valueOf(connectSize));
nodeScoreCache.save(nodeJoin);
//加层判断,把不满足缩容条件的缓存删除 连接数 > 最低阈值
if (connectSize > 20 && nodeReduced.isWhether(instance.getInstanceId())){
nodeReduced.remove(instance.getInstanceId());
}
//判断是否达到缩容条件 节点数量 > 1 或 连接数 < 21 必须满足节点数量在两个及以上且连接数低于21
if (instanceLists.size() > 1 && connectSize < 21){
//调用缩容方法 记录
contractionVolume.reduction(instance.getInstanceId());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//封装节点数量和节点连接总数
TotalNumber totalNumber = new TotalNumber();
totalNumber.setConnectionTotal(connectionTotal);
totalNumber.setNodeNumber(nodeNumber);
//调用扩容方法去判断是否需要扩缩容
contractionVolume.contractionVolume(totalNumber);
}
}

View File

@ -0,0 +1,134 @@
package com.guo.task.Contraction;
import com.guo.aly.ALYunEcsService;
import com.guo.common.model.TotalNumber;
import com.guo.gateway.cache.NodeReduced;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @author gxb
* @description
* @date 2024-04-18 19:52
*/
@AllArgsConstructor
@Component
@Log4j2
public class ContractionVolume {
/**
*
*/
private final static Long Maxnumber = 100L;
/**
* 60%80%
*/
private final static Long Intermediate = 60L;
private final static Long Maximum = 80L;
@Autowired
private ALYunEcsService alYunEcsService;
/**
*
*/
private final NodeReduced nodeReduced;
/**
*
* @param nodeId
*/
public void reduction(String nodeId){
//非空判断
if (null != nodeId){
//判断是否被标记过
if (nodeReduced.isWhether(nodeId)){
//查询剩余过期时间 秒
Long expire = nodeReduced.remainingTime(nodeId);
//获取 5分钟的秒值
long fiveMinutesSeconds = TimeUnit.MINUTES.toSeconds(5);
//打印
log.info("空闲节点 " + nodeId + "的剩余时间:" + expire + "/秒");
//比较 剩余时间 小于5分钟
if (expire < fiveMinutesSeconds){
//数据迁移 释放节点
}
}
//记录
nodeReduced.put(nodeId);
}
}
/**
*
* @param totalNumber
*/
public void contractionVolume(TotalNumber totalNumber){
//特殊情况 无节点
if (totalNumber.getNodeNumber() == 0L){
//无则创建两台实力
log.error("当前未存在节点信息");
try {
//创建实例方法 【2台】
alYunEcsService.createAnServers();
} catch (Exception e) {
log.error("扩容失败!!!!!");
e.printStackTrace();
}
//返回
return;
}
//调用计算
Long value = this.percentage(totalNumber);
//判断达到60%
if (value >= Intermediate && value < Maximum){
//当节点负载达到 60%时,调用扩容一台方法
log.info("Node 节点负载达到 " + value + "%,达到扩容一台的条件☑");
try {
//创建实例方法 【1台】
alYunEcsService.createAnServer();
} catch (Exception e) {
log.error("扩容失败!!!!!");
e.printStackTrace();
}
}
//判断达到80%
if (value >= Maximum){
//当节点负载达到 80%时,调用扩容一台方法
log.info("Node 节点负载达到 " + value + "%,达到扩容一台的条件☑");
try {
//创建实例方法 【2台】
alYunEcsService.createAnServers();
} catch (Exception e) {
log.error("扩容失败!!!!!");
e.printStackTrace();
}
}
}
/**
*
*/
private Long percentage(TotalNumber totalNumber){
//获取节点数量
Long nodeNumber = totalNumber.getNodeNumber();
//根据nodeNumber去获取最大节点数 默认 100
Long sumNodeNumber = nodeNumber * Maxnumber;
//获取节点连接总数
Long connectionTotal = totalNumber.getConnectionTotal();
//计算当前负载情况
double loadPercentage = (double)connectionTotal / sumNodeNumber;
//进行四舍五入取整
long roundLoadPercentage = Math.round(loadPercentage) * 100;
//返回百分比
return roundLoadPercentage;
}
}

View File

@ -0,0 +1,22 @@
server:
port: 9209
spring:
redis:
host: 127.0.0.1
port: 6379
aliyun:
accessKeyId: LTAI5tPDLpTbAX9bUSrTSrPH
accessKeySecret: rbLG6bh8ZSttUPMxUspk9j8XLzvLU0
regionId: cn-shanghai
image-id: m-uf6hu0jwys1efmiemfxl
instance-type: ecs.e-c1m1.large
security-group-id: sg-uf6bj6vxp8ruhvffdsau
v-switch-id: vsw-uf6sfq669js64lwke0isv
internet-max-bandwidth-out: 2
internet-charge-type: PayByTraffic
size: 20
category: cloud_essd
instance-charge-type: PostPaid