master
commit
43295537c9
|
@ -0,0 +1,231 @@
|
|||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.muyu</groupId>
|
||||
<artifactId>mqtt</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>mqtt</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<spring-boot.version>2.6.13</spring-boot.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
|
||||
|
||||
|
||||
|
||||
<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>com.aliyun</groupId>
|
||||
<artifactId>credentials-java</artifactId>
|
||||
<version>LATEST</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>tea-openapi</artifactId>
|
||||
<version>0.2.8</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>dysmsapi20170525</artifactId>
|
||||
<version>2.0.24</version>
|
||||
</dependency>
|
||||
<!-- V2.0 SDK -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>ecs20140526</artifactId>
|
||||
<version>3.1.12</version>
|
||||
</dependency>
|
||||
<!-- V1.0 SDK -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
<version>4.6.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-ecs</artifactId>
|
||||
<version>4.24.59</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</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.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>5.3.31</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<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>
|
|
@ -0,0 +1,15 @@
|
|||
package com.muyu;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@EnableScheduling
|
||||
@SpringBootApplication
|
||||
public class Ynpplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Ynpplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,88 @@
|
|||
package com.muyu.common.aly;
|
||||
|
||||
import com.aliyun.ecs20140526.Client;
|
||||
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
|
||||
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
|
||||
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
|
||||
import com.aliyun.tea.TeaException;
|
||||
import com.muyu.common.config.AliConfig;
|
||||
import com.muyu.common.domain.InstanceInfo;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @ClassName AliYunRcsService //类名称
|
||||
* @Author: yannan //作者
|
||||
* @CreateDate: 2024/4/16 20:49 //创建时间
|
||||
* 阿里云ECS服务器OpenAPI调出
|
||||
*/
|
||||
@Service
|
||||
public class AliYunRcsService {
|
||||
|
||||
|
||||
private final AliConfig aliConfig;
|
||||
|
||||
private final Client client;
|
||||
|
||||
|
||||
|
||||
public AliYunRcsService(AliConfig aliConfig, Client client){
|
||||
this.aliConfig = aliConfig;
|
||||
this.client=client;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public List<InstanceInfo> selectECS(String instanceName) throws Exception {
|
||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
|
||||
.setRegionId(aliConfig.getRegionId())
|
||||
.setInstanceName(instanceName)
|
||||
.setPageSize(10);
|
||||
|
||||
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
|
||||
|
||||
List<InstanceInfo> instanceInfos = new ArrayList<>(); // 用于存储查询到的实例信息
|
||||
|
||||
try {
|
||||
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
|
||||
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
|
||||
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
|
||||
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instanceList = instances.getInstance();
|
||||
|
||||
// 修改 selectECS 方法中 IP 地址的处理部分
|
||||
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance item : instanceList) {
|
||||
InstanceInfo instanceInfo = new InstanceInfo();
|
||||
instanceInfo.setInstanceId(item.getInstanceId());
|
||||
instanceInfo.setInstanceName(item.getInstanceName());
|
||||
// 将 IP 地址对象转换为字符串,并存储到 InstanceInfo 对象中
|
||||
// 在您的代码中将 IP 地址转换为字符串的部分可以改为以下方式
|
||||
|
||||
|
||||
|
||||
String publicIpAddress = item.getPublicIpAddress().getIpAddress().toString();
|
||||
// 去掉方括号
|
||||
publicIpAddress = publicIpAddress.substring(1, publicIpAddress.length() - 1);
|
||||
instanceInfo.setPublicIpAddress(publicIpAddress);
|
||||
|
||||
String privateIpAddress = item.getVpcAttributes().getPrivateIpAddress().ipAddress.toString();
|
||||
// 去掉方括号
|
||||
privateIpAddress = privateIpAddress.substring(1, privateIpAddress.length() - 1);
|
||||
instanceInfo.setPrivateIpAddress(privateIpAddress);
|
||||
instanceInfos.add(instanceInfo);
|
||||
}
|
||||
} catch (TeaException error) {
|
||||
error.printStackTrace();
|
||||
// 异常处理
|
||||
} catch (Exception _error) {
|
||||
_error.printStackTrace();
|
||||
// 异常处理
|
||||
}
|
||||
|
||||
return instanceInfos;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.muyu.common.config;
|
||||
|
||||
import com.aliyun.ecs20140526.Client;
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* @ClassName AliConfig //类名称
|
||||
* @Author: yn //作者
|
||||
* @CreateDate: 2024-4-16 20:41 //创建时间
|
||||
*/
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "config.aly")
|
||||
@Data
|
||||
public class AliConfig {
|
||||
|
||||
|
||||
/**
|
||||
* access-key-id
|
||||
*/
|
||||
private String accessKeyId;
|
||||
|
||||
/**
|
||||
*access-key-secret
|
||||
*/
|
||||
private String accessKeySecret;
|
||||
|
||||
|
||||
/**
|
||||
* 地域ID
|
||||
*/
|
||||
private String regionId;
|
||||
|
||||
|
||||
|
||||
@Bean
|
||||
public static Client createClient(AliConfig aliConfig) throws Exception {
|
||||
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
|
||||
// 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
|
||||
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
|
||||
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
|
||||
.setAccessKeyId(aliConfig.accessKeyId)
|
||||
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
|
||||
.setAccessKeySecret(aliConfig.getAccessKeySecret());
|
||||
// Endpoint 请参考 https://api.aliyun.com/product/Ecs
|
||||
config.endpoint = "ecs.cn-shanghai.aliyuncs.com";
|
||||
return new Client(config);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.muyu.common.config;
|
||||
|
||||
import com.aliyun.ecs20140526.Client;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-13 12:40
|
||||
*/
|
||||
public class ClientConfig {
|
||||
|
||||
|
||||
|
||||
public static Client createClient() throws Exception {
|
||||
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
|
||||
// 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
|
||||
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
|
||||
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
|
||||
.setAccessKeyId("LTAI5tPDLpTbAX9bUSrTSrPH")
|
||||
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
|
||||
.setAccessKeySecret("rbLG6bh8ZSttUPMxUspk9j8XLzvLU0");
|
||||
// Endpoint 请参考 https://api.aliyun.com/product/Ecs
|
||||
config.endpoint = "ecs.cn-shanghai.aliyuncs.com";
|
||||
return new Client(config);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,329 @@
|
|||
package com.muyu.common.config;
|
||||
|
||||
import com.aliyun.ecs20140526.Client;
|
||||
import com.aliyun.ecs20140526.models.*;
|
||||
import com.aliyun.tea.TeaException;
|
||||
import com.aliyun.tea.TeaModel;
|
||||
import com.aliyun.teaopenapi.models.Config;
|
||||
|
||||
import com.muyu.common.contents.CreateContents;
|
||||
import com.muyu.common.domain.CreateVo;
|
||||
import com.muyu.common.domain.DeleteServer;
|
||||
import com.muyu.common.domain.Icreate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description 实例创建-查询-删除
|
||||
* @date 2024-04-12 15:10
|
||||
*/
|
||||
@Component
|
||||
public class CreateAnConfig {
|
||||
|
||||
|
||||
/**
|
||||
* Initialization 初始化公共请求参数
|
||||
*/
|
||||
public static Client Initialization(String regionId) throws Exception {
|
||||
Config config = new Config();
|
||||
// 您的AccessKey ID
|
||||
config.accessKeyId = CreateContents.ACCESSKEYIDDATA;
|
||||
// 您的AccessKey Secret
|
||||
config.accessKeySecret = CreateContents.ACCESSKEYSECRETDATA;
|
||||
// 您的可用区ID
|
||||
config.regionId = regionId;
|
||||
return new Client(config);
|
||||
}
|
||||
|
||||
|
||||
|
||||
static int i = 1;
|
||||
|
||||
public static void main(String[] args_) throws Exception {
|
||||
System.setOut(new java.io.PrintStream(System.out, true, "UTF-8"));
|
||||
List<String> args = java.util.Arrays.asList(args_);
|
||||
Client client = ClientConfig.createClient();
|
||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
|
||||
.setRegionId("cn-shanghai")
|
||||
.setInstanceName("Test-server")
|
||||
.setPageSize(10);
|
||||
|
||||
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
|
||||
|
||||
try {
|
||||
// 复制代码运行请自行打印 API 的返回值
|
||||
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
|
||||
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
|
||||
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
|
||||
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instance = instances.getInstance();
|
||||
instance.stream().forEach(item->{
|
||||
System.out.println("实例{" + i + "}的ID:" + item.getInstanceId());
|
||||
System.out.println("名称:" + item.getInstanceName());
|
||||
System.out.println("地域ID:" + item.getRegionId());
|
||||
System.out.println("状态:" + item.getStatus());
|
||||
System.out.println("类型:" + item.getInstanceType());
|
||||
System.out.println("CPU核心数:" + item.getCpu());
|
||||
System.out.println("内存大小:" + item.getMemory() + "MB");
|
||||
System.out.println("磁盘大小:" + item.getLocalStorageCapacity() + "G");
|
||||
System.out.println("操作系统:" + item.getOSName());
|
||||
System.out.println("网络类型:" + item.getInstanceNetworkType());
|
||||
System.out.println("公网出带宽值:" + item.getInternetMaxBandwidthOut() + "Mbit/s");
|
||||
System.out.println("公网入带宽值:" + item.getInternetMaxBandwidthIn() + "Mbit/s");
|
||||
System.out.println("公网IP:" + item.getPublicIpAddress().getIpAddress());
|
||||
System.out.println("私网IP:" + item.getVpcAttributes().getPrivateIpAddress().ipAddress);
|
||||
System.out.println("专有网络VPCID:" + item.getVpcAttributes().getVpcId());
|
||||
System.out.println("安全组ID:" + item.getSecurityGroupIds().getSecurityGroupId());
|
||||
System.out.println("创建时间:" + item.getCreationTime());
|
||||
System.out.println("到期时间:" + item.getExpiredTime());
|
||||
System.out.println("是否可以回收:" + (item.getRecyclable()?"是":"否") + "\n\n");
|
||||
i++;
|
||||
|
||||
});
|
||||
} catch (TeaException error) {
|
||||
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
|
||||
// 错误 message
|
||||
System.out.println(error.getMessage());
|
||||
// 诊断地址
|
||||
System.out.println(error.getData().get("Recommend"));
|
||||
com.aliyun.teautil.Common.assertAsString(error.message);
|
||||
} catch (Exception _error) {
|
||||
TeaException error = new TeaException(_error.getMessage(), _error);
|
||||
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
|
||||
// 错误 message
|
||||
System.out.println(error.getMessage());
|
||||
// 诊断地址
|
||||
System.out.println(error.getData().get("Recommend"));
|
||||
com.aliyun.teautil.Common.assertAsString(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 查询实例方法
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void findByCreate(CreateVo createVo) throws Exception {
|
||||
//java.util.List<String> args = java.util.Arrays.asList(args_);
|
||||
// 地域Id
|
||||
//String regionId = "cn-shanghai";
|
||||
String regionId = createVo.getRedionId();
|
||||
// 要查询的资源类型。取值范围:
|
||||
// Zone:可用区。
|
||||
// IoOptimized:I/O 优化。
|
||||
// InstanceType:实例规格。
|
||||
// SystemDisk:系统盘。
|
||||
// DataDisk:数据盘。
|
||||
// Network:网络类型。
|
||||
// ddh:专有宿主机。
|
||||
//String destinationResource = "InstanceType";
|
||||
String destinationResource = createVo.getDestinationResource();
|
||||
// 是否为I/O优化实例
|
||||
// optimized:I/O优化
|
||||
// none:非IO优化
|
||||
//String ioOptimized = "optimized";
|
||||
String ioOptimized = createVo.getIoOptimized();
|
||||
// 实例规格
|
||||
//说明: 如果您指定了InstanceType,则无法指定Cores或者Memory。
|
||||
//String instanceType = "ecs.u1-c1m1.large";
|
||||
String instanceType = createVo.getInstanceType();
|
||||
Client client = CreateAnConfig.Initialization(regionId);
|
||||
// 查询指定地域下所有可用区的库存供应情况
|
||||
CreateAnConfig.DescribeAvailableResource(client, regionId, destinationResource, ioOptimized, instanceType);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* DescribeAvailableResource 查询指定地域下所有可用区的库存供应情况
|
||||
*/
|
||||
public static void DescribeAvailableResource(Client client, String regionId, String destinationResource, String ioOptimized, String instanceType) throws Exception {
|
||||
System.setOut(new java.io.PrintStream(System.out, true, "UTF-8"));
|
||||
DescribeAvailableResourceRequest request = new DescribeAvailableResourceRequest()
|
||||
.setRegionId(regionId)
|
||||
.setDestinationResource(destinationResource)
|
||||
.setIoOptimized(ioOptimized)
|
||||
.setInstanceType(instanceType);
|
||||
try {
|
||||
com.aliyun.teaconsole.Client.log("--------------------查询" + regionId + "地域下所有可用区的" + instanceType + "库存供应情况:--------------------");
|
||||
DescribeAvailableResourceResponse responces = client.describeAvailableResource(request);
|
||||
com.aliyun.teaconsole.Client.log("--------------------查询结果:" + com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(responces.body.availableZones)) + "--------------------");
|
||||
} catch (TeaException error) {
|
||||
com.aliyun.teaconsole.Client.log("--------------------查询失败:" + com.aliyun.teautil.Common.toJSONString(error.code) + "--------------------");
|
||||
|
||||
} catch (Exception _error) {
|
||||
TeaException error = new TeaException(_error.getMessage(), _error);
|
||||
com.aliyun.teaconsole.Client.log("--------------------查询失败:" + com.aliyun.teautil.Common.toJSONString(error.code) + "--------------------");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建实例方法
|
||||
* @param icreate
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String createAnServer(Icreate icreate) throws Exception {
|
||||
// java.util.List<String> args = java.util.Arrays.asList(args_);
|
||||
// 地域Id
|
||||
//String regionId = "cn-shanghai";
|
||||
String regionId = icreate.getRehionId();
|
||||
// 镜像 ID,启动实例时选择的镜像资源。
|
||||
// String imageId = "m-uf6elrscl3c9wk6o762l";
|
||||
String imageId = icreate.getImageId();
|
||||
// 实例规格
|
||||
//String instanceType = "ecs.u1-c1m1.large";
|
||||
String instanceType = icreate.getInstanceType();
|
||||
// 新创建实例所属于的安全组 ID。
|
||||
//String securityGroupId = "sg-uf6bj6vxp8ruhvffdsau";
|
||||
String securityGroupId = icreate.getSecurityGroupId();
|
||||
// 虚拟交换机 ID。
|
||||
//String vSwitchId = "vsw-uf66jtgij0ptqxf1ix6l7 ";
|
||||
String vSwitchId = icreate.getVSwitchId();
|
||||
// 公网出带宽最大值,单位为 Mbit/s。取值范围:0~100。 默认值:0。
|
||||
//Integer internetMaxBandwidthOut = Integer.parseInt("2");
|
||||
Integer internetMaxBandwidthOut = Integer.parseInt(icreate.getInternetMaxBandwidthOut());
|
||||
// 网络计费类型。取值范围:
|
||||
// PayByBandwidth: 按固定带宽计费。
|
||||
// PayByTraffic: 按使用流量计费。
|
||||
// 默认值:PayByTraffic。
|
||||
//String internetChargeType = "PayByTraffic";
|
||||
String internetChargeType = icreate.getInternetChargeType();
|
||||
// 系统盘大小
|
||||
//String size = "20";
|
||||
String size = icreate.getSize();
|
||||
// 系统盘的云盘种类
|
||||
//String category = "cloud_essd";
|
||||
String category = icreate.getCategory();
|
||||
// ECS实例的计费方式
|
||||
// PrePaid:包年包月
|
||||
// PostPaid:按量付费
|
||||
//String instanceChargeType = "PostPaid";
|
||||
String instanceChargeType = icreate.getInstanceChargeType();
|
||||
Client client = CreateAnConfig.Initialization(regionId);
|
||||
// 批量创建实例
|
||||
String instances = CreateAnConfig.RunInstances(client, regionId, imageId, instanceType, securityGroupId, vSwitchId, internetMaxBandwidthOut, internetChargeType, size, category, instanceChargeType);
|
||||
|
||||
return instances;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* RunInstances 通过备选实例规格创建ECS实例最佳实践
|
||||
* 该场景中,在调用RunInstances创建ECS实例时判断是否发生库存不足等错误,如果发生错误,将调用DescribeRecommendInstanceType查询备选实例,然后通过备选实例规格重新创建ECS实例。
|
||||
*/
|
||||
public static 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实例。
|
||||
// amount = 5,
|
||||
// 如果缺少库存可以接受的最低创建数量。
|
||||
// minAmount = 2,
|
||||
// 打开预检参数功能,不会实际创建ECS实例,只检查参数正确性、用户权限或者ECS库存等问题。
|
||||
// 实际情况下,设置了DryRun参数后,Amount必须为1,MinAmount必须为空,您可以根据实际需求修改代码。
|
||||
.setDryRun(false)
|
||||
.setSystemDisk(new RunInstancesRequest.RunInstancesRequestSystemDisk()
|
||||
.setSize(size)
|
||||
.setCategory(category));
|
||||
RunInstancesResponse responces = client.runInstances(request1);
|
||||
try {
|
||||
com.aliyun.teaconsole.Client.log("--------------------批量创建实例开始--------------------");
|
||||
|
||||
com.aliyun.teaconsole.Client.log("--------------------创建实例成功,实例ID:" + com.aliyun.teautil.Common.toJSONString(responces.body.instanceIdSets.instanceIdSet) + "--------------------");
|
||||
} catch (TeaException error) {
|
||||
com.aliyun.teaconsole.Client.log("--------------------创建实例失败:" + error+ "--------------------");
|
||||
} catch (Exception _error) {
|
||||
TeaException error = new TeaException(_error.getMessage(), _error);
|
||||
com.aliyun.teaconsole.Client.log("--------------------创建实例失败:" +error + "--------------------");
|
||||
|
||||
|
||||
}
|
||||
return com.aliyun.teautil.Common.toJSONString(responces.body.instanceIdSets.instanceIdSet);
|
||||
}
|
||||
|
||||
public static 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 = com.aliyun.teautil.Common.toJSONString(com.aliyun.darabonbastring.Client.split(instanceIds, ",", 50));
|
||||
}
|
||||
|
||||
DescribeInstancesResponse resp = client.describeInstances(req);
|
||||
com.aliyun.teaconsole.Client.log("--------------------查询需要删除的实例--------------------");
|
||||
return resp;
|
||||
}
|
||||
|
||||
public static void ModifyInstanceAttribute(Client client, String instatnceId) throws Exception {
|
||||
ModifyInstanceAttributeRequest req = new ModifyInstanceAttributeRequest()
|
||||
.setInstanceId(instatnceId)
|
||||
.setDeletionProtection(false);
|
||||
client.modifyInstanceAttribute(req);
|
||||
com.aliyun.teaconsole.Client.log("--------------------" + instatnceId + "释放保护取消成功--------------------");
|
||||
}
|
||||
|
||||
public static 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);
|
||||
com.aliyun.teaconsole.Client.log("--------------------实例释放成功--------------------");
|
||||
com.aliyun.teaconsole.Client.log(com.aliyun.teautil.Common.toJSONString(com.aliyun.teautil.Common.toMap(resp)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除实力
|
||||
* @param deleteServer
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void DeleServerCreateAn(DeleteServer deleteServer) throws Exception {
|
||||
// 区域ID
|
||||
//String regionId = "cn-shanghai";
|
||||
String regionId = deleteServer.getRegionId();
|
||||
// 多个实例ID,用英文逗号分隔
|
||||
//String instanceIds = "i-uf6h4s0jtpvobykd7vzc";
|
||||
String instanceIds = deleteServer.getInstanceIds();
|
||||
// 实例名称,支持使用通配符*进行模糊搜索
|
||||
//String instanceName = "MyFirstEcsInstance";
|
||||
String instanceName = deleteServer.getInstanceName();
|
||||
// 强制删除有删除保护的机器
|
||||
//String deleteProtected = "true";
|
||||
String deleteProtected = deleteServer.getDeleteProtected();
|
||||
// 强制删除运行中的机器
|
||||
//String force = "true";
|
||||
String force = deleteServer.getForce();
|
||||
Client client = CreateAnConfig.Initialization(regionId);
|
||||
if (com.aliyun.teautil.Common.equalString(deleteProtected, force)) {
|
||||
DescribeInstancesResponse describeInstancesResp = CreateAnConfig.DescribeInstances(client, regionId, instanceIds, instanceName);
|
||||
instanceIds = "";
|
||||
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : describeInstancesResp.body.instances.instance) {
|
||||
instanceIds = "" + instance.instanceId + "," + instanceIds + "";
|
||||
if (instance.deletionProtection) {
|
||||
CreateAnConfig.ModifyInstanceAttribute(client, instance.instanceId);
|
||||
}
|
||||
|
||||
}
|
||||
instanceIds = com.aliyun.darabonbastring.Client.subString(instanceIds, 0, -1);
|
||||
}
|
||||
|
||||
if (com.aliyun.teautil.Common.empty(instanceIds)) {
|
||||
com.aliyun.teaconsole.Client.log("--------------------无有效实例可删除--------------------");
|
||||
return ;
|
||||
}
|
||||
|
||||
CreateAnConfig.DeleteInstances(client, regionId, instanceIds, force);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package com.muyu.common.config;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.muyu.common.config;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.muyu.common.contents;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-12 16:22
|
||||
*/
|
||||
public class CreateContents {
|
||||
|
||||
//AccessKey ID值
|
||||
public static final String ACCESSKEYIDDATA = "LTAI5tPDLpTbAX9bUSrTSrPH";
|
||||
//您的AccessKey Secret
|
||||
public static final String ACCESSKEYSECRETDATA = "rbLG6bh8ZSttUPMxUspk9j8XLzvLU0";
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.muyu.common.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;
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.muyu.common.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;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-12 16:17
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@SuperBuilder
|
||||
public class CreateVo {
|
||||
|
||||
//地域ID
|
||||
private String redionId = "cn-shanghai";
|
||||
|
||||
//查询资源类型,取值范围
|
||||
private String destinationResource = "InstanceType";
|
||||
|
||||
//是否为I/O优化实例
|
||||
private String ioOptimized = "optimized";
|
||||
|
||||
//实例规格
|
||||
private String instanceType = "ecs.u1-c1m1.large";
|
||||
|
||||
private String instanceId;
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-12 19:14
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@SuperBuilder
|
||||
public class DeleteServer {
|
||||
//区域ID
|
||||
private String regionId = "cn-shanghai";
|
||||
|
||||
//多个实例ID,英文逗号隔开
|
||||
private String instanceIds;
|
||||
|
||||
//实例名称,支持模糊查
|
||||
private String instanceName;
|
||||
|
||||
//是否强制删除有删除保护的机器 默认 true
|
||||
private String deleteProtected="true";
|
||||
|
||||
//是否强制删除运行中的机器 默认 true
|
||||
private String force = "true";
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.Data; /**
|
||||
* 节点状态
|
||||
*/
|
||||
@Data
|
||||
public class FlowInfo {
|
||||
/**
|
||||
* 上次读取吞吐量
|
||||
*/
|
||||
private String lastReadThroughput;
|
||||
/**
|
||||
* 上次写入吞吐量
|
||||
*/
|
||||
private String lastWriteThroughput;
|
||||
/**
|
||||
* 读取总吞吐量
|
||||
*/
|
||||
private String readBytesHistory;
|
||||
/**
|
||||
* 实写字节
|
||||
*/
|
||||
private String realWriteBytes;
|
||||
/**
|
||||
* 写入总吞吐量
|
||||
*/
|
||||
private String writeBytesHistory;
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-12 16:25
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@SuperBuilder
|
||||
public class Icreate {
|
||||
|
||||
//地域ID
|
||||
private String rehionId = "cn-shanghai";
|
||||
|
||||
//镜像ID
|
||||
private String imageId = "m-uf6hu0jwys1efmiemfxl";
|
||||
|
||||
//实例规格
|
||||
private String instanceType = "ecs.e-c1m1.large";
|
||||
|
||||
//安全组ID
|
||||
private String securityGroupId = "sg-uf6bj6vxp8ruhvffdsau";
|
||||
|
||||
//虚拟交换机ID
|
||||
private String vSwitchId = "vsw-uf6sfq669js64lwke0isv";
|
||||
|
||||
//公网出带宽最大值,单位为 Mbit/s。取值范围:0~100。 默认值:0。
|
||||
private String internetMaxBandwidthOut = "2";
|
||||
|
||||
//网络计费类型,取值范围
|
||||
private String internetChargeType = "PayByTraffic";
|
||||
|
||||
//系统盘大小
|
||||
private String size = "20";
|
||||
|
||||
//系统盘的云盘种类
|
||||
private String category = "cloud_essd";
|
||||
|
||||
//ECS实例的计费方式
|
||||
private String instanceChargeType = "PostPaid";
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.ToString;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-13 18:41
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@SuperBuilder
|
||||
@ToString
|
||||
public class InstanceInfo{
|
||||
private String instanceId;
|
||||
private String instanceName;
|
||||
private String publicIpAddress; // 将数据类型修改为字符串
|
||||
private String privateIpAddress; // 将数据类型修改为字符串
|
||||
|
||||
|
||||
public void setPublicIpAddress(String ipAddress) {
|
||||
this.publicIpAddress = ipAddress;
|
||||
}
|
||||
|
||||
public void setPrivateIpAddress(String ipAddress) {
|
||||
this.privateIpAddress = ipAddress;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.SuperBuilder;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-15 10:57
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@SuperBuilder
|
||||
public class IsanJoin {
|
||||
//节点ID
|
||||
private String insanId;
|
||||
//连接数
|
||||
private Integer countConntion;
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.muyu.common.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;
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.muyu.common.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;
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.muyu.common.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-13 8:33
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class NodeRegReq {
|
||||
|
||||
/**
|
||||
* 客户端ID
|
||||
*/
|
||||
private String clientId;
|
||||
|
||||
/**
|
||||
* token
|
||||
*/
|
||||
private String token;
|
||||
}
|
|
@ -0,0 +1,336 @@
|
|||
package com.muyu.common.redis;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* 缓存基本的对象,Integer、String、实体类等
|
||||
*
|
||||
* @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());
|
||||
}
|
||||
|
||||
/**
|
||||
* 减少序列值
|
||||
* @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();
|
||||
}
|
||||
/**
|
||||
* 缓存基本的对象,Integer、String、实体类等
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获得缓存的基本对象。
|
||||
*
|
||||
* @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);
|
||||
}
|
||||
/**
|
||||
* 缓存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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.muyu.common.utils;
|
||||
|
||||
|
||||
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 = 800;
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int code;
|
||||
|
||||
private String msg;
|
||||
|
||||
private T data;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,185 @@
|
|||
package com.muyu.controller;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.muyu.common.redis.RedisService;
|
||||
import com.muyu.common.utils.Result;
|
||||
import com.muyu.common.domain.IsanJoin;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description 负载中心 算法
|
||||
* @date 2024-04-15 11:02
|
||||
*/
|
||||
@Component
|
||||
@RestController
|
||||
@RequestMapping("/vecOne")
|
||||
public class AlController {
|
||||
@Autowired
|
||||
private RedisService redisService;
|
||||
|
||||
@RequestMapping("/vecTwo")
|
||||
public Result contextLoads() {
|
||||
//初始化序列
|
||||
redisService.setCacheObject("cursor", 0);
|
||||
|
||||
List<WorkGetWayNode> nodeIdList = new ArrayList<>();
|
||||
//获取缓存中值
|
||||
Set<Object> cacheSet = redisService.getCacheSet("Isantion:conntionCount");
|
||||
for (Object o : cacheSet) {
|
||||
String str = (String) o;
|
||||
IsanJoin isanJoin = JSONObject.parseObject(str, IsanJoin.class);
|
||||
nodeIdList.add(new WorkGetWayNode(isanJoin.getInsanId(), isanJoin.getCountConntion()));
|
||||
}
|
||||
|
||||
|
||||
// List<WorkGetWayNode> nodeIdList = new ArrayList<WorkGetWayNode>() {{
|
||||
// add(new WorkGetWayNode("work-gateway-node-A", 8));
|
||||
// add(new WorkGetWayNode("work-gateway-node-B", 12));
|
||||
// add(new WorkGetWayNode("work-gateway-node-C", 2));
|
||||
// add(new WorkGetWayNode("work-gateway-node-D", 39));
|
||||
// add(new WorkGetWayNode("work-gateway-node-E", 39));
|
||||
// }};
|
||||
|
||||
// 创建一个空列表用于存储节点ID
|
||||
List<String> loadNodelist = new ArrayList<>();
|
||||
// 计算权重总和
|
||||
long count = nodeIdList.stream().mapToInt(WorkGetWayNode::getWeight).count();
|
||||
|
||||
// 若总权重小于100,则重新分配权重使之等于100
|
||||
if (count < 100) {
|
||||
List<WorkGetWayNode> list = nodeIdList.stream()
|
||||
.sorted(((o1, o2) -> o2.getWeight() - o1.getWeight()))
|
||||
.toList();
|
||||
|
||||
int countWeight = 0;
|
||||
for (long i = 0; i < 100; i++) {
|
||||
WorkGetWayNode workGetWayNode = list.get(countWeight++ % list.size());
|
||||
workGetWayNode.setWeight(workGetWayNode.getWeight() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 循环分配任务给各节点,直到所有节点权重为0
|
||||
whFor:
|
||||
while (true) {
|
||||
for (WorkGetWayNode workGetWayNode : nodeIdList) {
|
||||
int weight = workGetWayNode.getWeight();
|
||||
if (weight > 0) {
|
||||
loadNodelist.add(workGetWayNode.getNodeId());
|
||||
workGetWayNode.setWeight(weight - 1);
|
||||
}
|
||||
int sum = nodeIdList.stream()
|
||||
.mapToInt(WorkGetWayNode::getWeight)
|
||||
.sum();
|
||||
if (sum <= 0) {
|
||||
break whFor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清空并更新节点列表缓存
|
||||
redisService.deleteObject("work:node:gateway");
|
||||
redisService.setCacheList("work:node:gateway", loadNodelist);
|
||||
|
||||
// 使用计数器控制并发执行任务
|
||||
CountDownLatch downLatch = new CountDownLatch(3000);
|
||||
|
||||
// 创建并启动线程执行任务
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
// 增加序列值
|
||||
Long cursor = redisService.increment("cursor", 1L);
|
||||
// 获取节点ID
|
||||
String nodeId = redisService.getCacheList("work:node:gateway", cursor % 100);
|
||||
System.out.println(Thread.currentThread().getName() + ":" + cursor + "--------" + nodeId);
|
||||
// 执行任务
|
||||
stiNode.sti(nodeId);
|
||||
downLatch.countDown();
|
||||
}
|
||||
}).start();
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
//增加序列值
|
||||
Long cursor = redisService.increment("cursor", 1L);
|
||||
String nodeId = redisService.getCacheList("work:node:gateway", cursor % 100);
|
||||
System.out.println(Thread.currentThread().getName() + ":" + cursor + "--------" + nodeId);
|
||||
stiNode.sti(nodeId);
|
||||
downLatch.countDown();
|
||||
}
|
||||
}).start();
|
||||
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
//增加序列值
|
||||
Long cursor = redisService.increment("cursor", 1L);
|
||||
String nodeId = redisService.getCacheList("work:node:gateway", cursor % 100);
|
||||
System.out.println(Thread.currentThread().getName() + ":" + cursor + "--------" + nodeId);
|
||||
stiNode.sti(nodeId);
|
||||
downLatch.countDown();
|
||||
}
|
||||
}).start();
|
||||
|
||||
try {
|
||||
downLatch.await();
|
||||
|
||||
Map<String, Long> show = stiNode.show();
|
||||
|
||||
Map.Entry<String, Long> maxEntry = show.entrySet().stream()
|
||||
.max(Comparator.comparing(Map.Entry::getValue))
|
||||
.orElse(null);
|
||||
|
||||
if (maxEntry != null) {
|
||||
System.out.println("<<<<<<<<<<<<<<Key with maximum value: " + maxEntry.getKey());
|
||||
System.out.println("<<<<<<<<<<<<<<Maximum value: " + maxEntry.getValue());
|
||||
return Result.success(maxEntry.getKey());
|
||||
} else {
|
||||
System.out.println("Map is empty");
|
||||
}
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
|
||||
return Result.error();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class stiNode {
|
||||
private static Map<String, Integer> stiNodeMqp = new HashMap<>();
|
||||
|
||||
public synchronized static void sti(String nodeId) {
|
||||
Integer stiCount = stiNodeMqp.getOrDefault(nodeId, 0);
|
||||
stiNodeMqp.put(nodeId, stiCount + 1);
|
||||
}
|
||||
|
||||
|
||||
public static Map<String, Long> show() {
|
||||
Map<String, Long> addMap = new HashMap<>();
|
||||
stiNodeMqp.forEach((key, val) -> {
|
||||
addMap.put(key,Long.valueOf(val));
|
||||
System.out.println(key + "-------" + val);
|
||||
});
|
||||
return addMap;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
class WorkGetWayNode {
|
||||
|
||||
private String nodeId;
|
||||
|
||||
private int Weight;
|
||||
|
||||
}
|
|
@ -0,0 +1,191 @@
|
|||
package com.muyu.controller;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
|
||||
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
|
||||
import com.aliyun.tea.TeaException;
|
||||
|
||||
|
||||
import com.muyu.common.config.ClientConfig;
|
||||
import com.muyu.common.config.CreateAnConfig;
|
||||
import com.muyu.common.redis.RedisService;
|
||||
import com.muyu.common.domain.Icreate;
|
||||
import com.muyu.common.domain.InstanceInfo;
|
||||
import com.muyu.common.domain.IsanJoin;
|
||||
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.util.*;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-13 12:46
|
||||
*/
|
||||
@Component
|
||||
@Log4j2
|
||||
public class LoadCenterController {
|
||||
|
||||
//定义一个值
|
||||
@Autowired
|
||||
private RedisService redisService;
|
||||
//车辆点击上线,通过负载中心,返回一个ip地址,请求连接到返回的ip地址
|
||||
|
||||
/**
|
||||
* 定时器扫描 是否需要创建节点
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Scheduled(cron = "0/5 * * * * ?")
|
||||
public void scheduleECS() throws Exception {
|
||||
|
||||
// 第一次进来,先查询是否存在收集节点 节点名称默认都为 “Myname”
|
||||
List<InstanceInfo> Instance = selectECS("Myname");
|
||||
|
||||
redisService.deleteObject("Isantion:conntionCount");
|
||||
|
||||
//不为空
|
||||
if (!Instance.isEmpty()){
|
||||
//遍历集合
|
||||
for (InstanceInfo instanceInfo : Instance) {
|
||||
//获取当前对象存入redis
|
||||
redisService.setCacheSets("Instance:ache", JSON.toJSONString(instanceInfo));
|
||||
}
|
||||
|
||||
//获取缓存中的对象
|
||||
List<String> cacheSets = redisService.getCacheSets("Instance:ache");
|
||||
|
||||
for (String cacheSet : cacheSets) {
|
||||
|
||||
String string = cacheSet;
|
||||
InstanceInfo instanClasss = JSONObject.parseObject(string, InstanceInfo.class);
|
||||
|
||||
|
||||
//获取每个FluxMQ运行信息
|
||||
String URL = "http://"+instanClasss.getPublicIpAddress()+":8080/public/cluster";
|
||||
//假设这里出现了超出预设连接数大于80%,则进行扩容
|
||||
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("当前:"+instanClasss.getPublicIpAddress()+",的连接数===="+connectSize);
|
||||
//存入收集节点ID:连接数
|
||||
IsanJoin isanJoin = new IsanJoin();
|
||||
isanJoin.setInsanId(instanClasss.getPublicIpAddress());
|
||||
isanJoin.setCountConntion(connectSize);
|
||||
redisService.setCacheSets("Isantion:conntionCount", JSON.toJSONString(isanJoin));
|
||||
//判断是否达到连接数80
|
||||
if (connectSize >= 1000) {
|
||||
//节点扩容
|
||||
try {
|
||||
Icreate icreate = new Icreate();
|
||||
String anServer = CreateAnConfig.createAnServer(icreate);
|
||||
log.info("扩容成功,实例ID为:{}", anServer);
|
||||
// 每次新增查询实例集合
|
||||
List<InstanceInfo> Instan = selectECS("Myname");
|
||||
//遍历集合
|
||||
for (InstanceInfo instanceInfo : Instan) {
|
||||
//新增存入缓存
|
||||
redisService.setCacheSets("Instance:ache", JSON.toJSONString(instanceInfo));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("扩容失败:" + e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// //没收集节点时创建一个实例
|
||||
// Icreate icreate = new Icreate();
|
||||
// //执行创建实例方法
|
||||
// String anServer = CreateAn.createAnServer(icreate);
|
||||
// //打印实例ID
|
||||
// log.info("扩容成功,实例ID为:{}", anServer);
|
||||
// // 执行查询实例集合
|
||||
// List<InstanceInfo> Instan = selectECS("Myname");
|
||||
// //遍历集合
|
||||
// for (InstanceInfo instanceInfo : Instan) {
|
||||
// //新增存入缓存
|
||||
// redisService.setCacheSets("Instance:ache", JSON.toJSONString(instanceInfo));
|
||||
// }
|
||||
//
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static List<InstanceInfo> selectECS(String instanceName) throws Exception {
|
||||
com.aliyun.ecs20140526.Client client = ClientConfig.createClient();
|
||||
com.aliyun.ecs20140526.models.DescribeInstancesRequest describeInstancesRequest = new com.aliyun.ecs20140526.models.DescribeInstancesRequest()
|
||||
.setRegionId("cn-shanghai")
|
||||
.setInstanceName(instanceName)
|
||||
.setPageSize(10);
|
||||
|
||||
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
|
||||
|
||||
List<InstanceInfo> instanceInfos = new ArrayList<>(); // 用于存储查询到的实例信息
|
||||
|
||||
try {
|
||||
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
|
||||
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
|
||||
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
|
||||
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instanceList = instances.getInstance();
|
||||
|
||||
// 修改 selectECS 方法中 IP 地址的处理部分
|
||||
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance item : instanceList) {
|
||||
InstanceInfo instanceInfo = new InstanceInfo();
|
||||
instanceInfo.setInstanceId(item.getInstanceId());
|
||||
instanceInfo.setInstanceName(item.getInstanceName());
|
||||
// 将 IP 地址对象转换为字符串,并存储到 InstanceInfo 对象中
|
||||
// 在您的代码中将 IP 地址转换为字符串的部分可以改为以下方式
|
||||
|
||||
|
||||
|
||||
String publicIpAddress = item.getPublicIpAddress().getIpAddress().toString();
|
||||
// 去掉方括号
|
||||
publicIpAddress = publicIpAddress.substring(1, publicIpAddress.length() - 1);
|
||||
instanceInfo.setPublicIpAddress(publicIpAddress);
|
||||
|
||||
String privateIpAddress = item.getVpcAttributes().getPrivateIpAddress().ipAddress.toString();
|
||||
// 去掉方括号
|
||||
privateIpAddress = privateIpAddress.substring(1, privateIpAddress.length() - 1);
|
||||
instanceInfo.setPrivateIpAddress(privateIpAddress);
|
||||
instanceInfos.add(instanceInfo);
|
||||
}
|
||||
} catch (TeaException error) {
|
||||
error.printStackTrace();
|
||||
// 异常处理
|
||||
} catch (Exception _error) {
|
||||
_error.printStackTrace();
|
||||
// 异常处理
|
||||
}
|
||||
|
||||
return instanceInfos;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package com.muyu.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-01 20:56
|
||||
*/
|
||||
@RestController
|
||||
public class VehicleController {
|
||||
|
||||
@PostMapping("/vehicle/online")
|
||||
public ResponseEntity<String> vahiclieOnline(
|
||||
@RequestParam String vin,
|
||||
@RequestParam String time,
|
||||
@RequestParam String randomString
|
||||
){
|
||||
//将请求发送到fluxmq节点
|
||||
boolean connected = sendRequestToFluxMQ(vin, time, randomString);
|
||||
|
||||
if (connected){
|
||||
//如果成功连接,则返回成功响应
|
||||
return ResponseEntity.ok("成功连接");
|
||||
}
|
||||
//连接失败,返回错误响应,客户端需要重新走流程
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body("链接失败");
|
||||
}
|
||||
|
||||
//将请求发送到fluxmq节点的方法
|
||||
private boolean sendRequestToFluxMQ(String vin,String time,String randomString){
|
||||
// 在这里实现将请求发送到 fluxmq 节点的逻辑
|
||||
// 可以使用相应的消息队列客户端来发送消息
|
||||
|
||||
// 这里只是一个示例,假设连接成功
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
/*
|
||||
* Copyright 2013-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.muyu.demos.web;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
|
||||
*/
|
||||
@Controller
|
||||
public class BasicController {
|
||||
|
||||
// http://127.0.0.1:8080/hello?name=lisi
|
||||
@RequestMapping("/hello")
|
||||
@ResponseBody
|
||||
public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
|
||||
return "Hello " + name;
|
||||
}
|
||||
|
||||
// http://127.0.0.1:8080/user
|
||||
@RequestMapping("/user")
|
||||
@ResponseBody
|
||||
public User user() {
|
||||
User user = new User();
|
||||
user.setName("theonefx");
|
||||
user.setAge(666);
|
||||
return user;
|
||||
}
|
||||
|
||||
// http://127.0.0.1:8080/save_user?name=newName&age=11
|
||||
@RequestMapping("/save_user")
|
||||
@ResponseBody
|
||||
public String saveUser(User u) {
|
||||
return "user will save: name=" + u.getName() + ", age=" + u.getAge();
|
||||
}
|
||||
|
||||
// http://127.0.0.1:8080/html
|
||||
@RequestMapping("/html")
|
||||
public String html(){
|
||||
return "index.html";
|
||||
}
|
||||
|
||||
@ModelAttribute
|
||||
public void parseUser(@RequestParam(name = "name", defaultValue = "unknown user") String name
|
||||
, @RequestParam(name = "age", defaultValue = "12") Integer age, User user) {
|
||||
user.setName("zhangsan");
|
||||
user.setAge(18);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* Copyright 2013-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.muyu.demos.web;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
|
||||
*/
|
||||
@Controller
|
||||
public class PathVariableController {
|
||||
|
||||
// http://127.0.0.1:8080/user/123/roles/222
|
||||
@RequestMapping(value = "/user/{userId}/roles/{roleId}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String getLogin(@PathVariable("userId") String userId, @PathVariable("roleId") String roleId) {
|
||||
return "User Id : " + userId + " Role Id : " + roleId;
|
||||
}
|
||||
|
||||
// http://127.0.0.1:8080/javabeat/somewords
|
||||
@RequestMapping(value = "/javabeat/{regexp1:[a-z-]+}", method = RequestMethod.GET)
|
||||
@ResponseBody
|
||||
public String getRegExp(@PathVariable("regexp1") String regexp1) {
|
||||
return "URI Part : " + regexp1;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
* Copyright 2013-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.muyu.demos.web;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
|
||||
*/
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Integer age;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.muyu.server;
|
||||
|
||||
import com.muyu.common.redis.RedisService;
|
||||
import com.muyu.common.utils.Result;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.data.redis.core.ZSetOperations;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-03-27 16:21
|
||||
*
|
||||
*
|
||||
* guoxubao.e3.luyouxia.net:12867 ->内网事件
|
||||
*
|
||||
* http://guoxubao.w1.luyouxia.net -》外网事件
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("reg")
|
||||
@Log4j2
|
||||
public class ClientRegController {
|
||||
|
||||
@Autowired
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Autowired
|
||||
private RedisService redisService;
|
||||
|
||||
private Set<String> tokenset = new HashSet<>();
|
||||
|
||||
/**
|
||||
* 申请注册接口 获取到token值
|
||||
* 申请走内网:guoxubao.e3.luyouxia.net:12867/reg/apply
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/apply")
|
||||
public Result applicationRegistartion(){
|
||||
//生成令牌 只能使用一次
|
||||
String token = UUID.randomUUID().toString().replaceAll("-","");
|
||||
|
||||
tokenset.add(token); //到时候存redis
|
||||
|
||||
log.info("程序生成令牌:{}",token);
|
||||
|
||||
return Result.success(token);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 注册收集节点
|
||||
* @return
|
||||
*/
|
||||
@PostMapping
|
||||
public Result reg(@RequestBody NodeRegReq nodeRegReq)
|
||||
{
|
||||
|
||||
//后期负载均衡
|
||||
ZSetOperations zSetOperations = redisService.opsForZSet();
|
||||
|
||||
zSetOperations.add("LocadKey",nodeRegReq.getClientId(),0.0);
|
||||
|
||||
|
||||
|
||||
//基本信息的存储
|
||||
ValueOperations opsedForValue = redisService.opsForValue();
|
||||
|
||||
opsedForValue.set(nodeRegReq.getClientId(),"存储客户端基本信息:ip,端口,负载");
|
||||
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户基本信息
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public Result getConnectionOption(@RequestParam("token")String token){
|
||||
//token验证检查令牌是否有效
|
||||
if (!tokenset.contains(token)){
|
||||
|
||||
//令牌无效,返回错误信息
|
||||
log.warn("无效的令牌:{}",token);
|
||||
|
||||
return Result.error("无效的令牌");
|
||||
}
|
||||
|
||||
//通过负载key拿到客户端ID
|
||||
ZSetOperations zSetOperations = redisService.opsForZSet();
|
||||
|
||||
ZSetOperations.TypedTuple fuzaiKey = zSetOperations.popMin("fuzaiKey");
|
||||
|
||||
//获取客户端ID
|
||||
String cliendId = (String) fuzaiKey.getValue();
|
||||
|
||||
//根据客户端ID获取存储的基本信息
|
||||
ValueOperations<String, String> opsedForValue = redisService.opsForValue();
|
||||
|
||||
//客户端的基本信息
|
||||
String s = opsedForValue.get(cliendId);
|
||||
|
||||
return Result.success(s);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.muyu.server;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 注册模型请求对象
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-03-27 17:27
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@Builder
|
||||
public class NodeRegReq {
|
||||
/**
|
||||
* 客户端ID
|
||||
*/
|
||||
private String clientId;
|
||||
private String token;
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
package com.muyu.test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author yn
|
||||
* @description TODO
|
||||
* @date 2024-04-13 9:39
|
||||
*/
|
||||
public class fluxmqTest {
|
||||
public static void main(String[] args) {
|
||||
// FluxMQ 注册接口 URL
|
||||
String fluxMQRegisterUrl = "http://43.143.161.183/register";
|
||||
|
||||
// 第一个请求获取 token 的 URL
|
||||
String getTokenUrl = "http://43.143.161.183/getToken";
|
||||
|
||||
try {
|
||||
// 发起第一个请求获取 token
|
||||
String token = getToken(getTokenUrl);
|
||||
|
||||
// 构建注册请求参数,包括 token
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("username", "your_username");
|
||||
params.put("email", "your_email@example.com");
|
||||
params.put("token", token);
|
||||
|
||||
// 发起注册请求
|
||||
String response = register(fluxMQRegisterUrl, params);
|
||||
|
||||
// 处理注册响应结果
|
||||
System.out.println("Response from FluxMQ registration: " + response);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// 发起第一个请求获取 token
|
||||
private static String getToken(String url) throws Exception {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
URL tokenUrl = new URL(url);
|
||||
conn = (HttpURLConnection) tokenUrl.openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
|
||||
String line;
|
||||
StringBuilder response = new StringBuilder();
|
||||
while ((line = reader.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
reader.close();
|
||||
|
||||
// 解析 JSON 响应获取 token
|
||||
// 这里假设 JSON 响应格式为 {"token": "your_token_value"}
|
||||
String jsonResponse = response.toString();
|
||||
return jsonResponse.substring(jsonResponse.indexOf(':') + 2, jsonResponse.lastIndexOf('"'));
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 发起注册请求
|
||||
private static String register(String url, Map<String, String> params) throws Exception {
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
URL registerUrl = new URL(url);
|
||||
conn = (HttpURLConnection) registerUrl.openConnection();
|
||||
|
||||
// 设置请求方法为 POST
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
||||
conn.setRequestProperty("Accept", "application/json");
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
// 构建请求参数
|
||||
StringBuilder postData = new StringBuilder();
|
||||
for (Map.Entry<String, String> param : params.entrySet()) {
|
||||
if (postData.length() != 0) {
|
||||
postData.append('&');
|
||||
}
|
||||
postData.append(param.getKey());
|
||||
postData.append('=');
|
||||
postData.append(param.getValue());
|
||||
}
|
||||
|
||||
// 将参数写入请求体
|
||||
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
|
||||
conn.getOutputStream().write(postDataBytes);
|
||||
|
||||
// 获取注册响应
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
|
||||
String line;
|
||||
StringBuilder response = new StringBuilder();
|
||||
while ((line = reader.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
reader.close();
|
||||
|
||||
return response.toString();
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
server:
|
||||
port: 9209
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: mqtt
|
||||
redis:
|
||||
host: 127.0.0.1
|
||||
|
||||
config:
|
||||
ali:
|
||||
access-key-id: LTAI5tPDLpTbAX9bUSrTSrPH
|
||||
access-key-secret: rbLG6bh8ZSttUPMxUspk9j8XLzvLU0
|
||||
region-id: cn-shanghai
|
|
@ -0,0 +1,6 @@
|
|||
<html>
|
||||
<body>
|
||||
<h1>hello word!!!</h1>
|
||||
<p>this is a html page</p>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,13 @@
|
|||
package com.muyu;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class MqttApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
server:
|
||||
port: 9209
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: mqtt
|
||||
redis:
|
||||
host: 127.0.0.1
|
||||
|
||||
config:
|
||||
ali:
|
||||
access-key-id: LTAI5tPDLpTbAX9bUSrTSrPH
|
||||
access-key-secret: rbLG6bh8ZSttUPMxUspk9j8XLzvLU0
|
||||
region-id: cn-shanghai
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,6 @@
|
|||
<html>
|
||||
<body>
|
||||
<h1>hello word!!!</h1>
|
||||
<p>this is a html page</p>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,5 @@
|
|||
#Generated by Maven
|
||||
#Wed Apr 17 10:20:56 CST 2024
|
||||
groupId=com.muyu
|
||||
artifactId=mqtt
|
||||
version=0.0.1-SNAPSHOT
|
|
@ -0,0 +1,45 @@
|
|||
com\muyu\common\domain\DeleteServer$DeleteServerBuilderImpl.class
|
||||
com\muyu\Ynpplication.class
|
||||
com\muyu\common\config\FastJson2JsonRedisSerializer.class
|
||||
com\muyu\server\ClientRegController.class
|
||||
com\muyu\common\domain\IsanJoin$IsanJoinBuilder.class
|
||||
com\muyu\common\domain\IsanJoin.class
|
||||
com\muyu\controller\LoadCenterController.class
|
||||
com\muyu\server\NodeRegReq.class
|
||||
com\muyu\common\domain\NodeRegReq.class
|
||||
com\muyu\common\redis\RedisService.class
|
||||
com\muyu\common\domain\CreateVo$CreateVoBuilderImpl.class
|
||||
com\muyu\common\domain\InstanceInfo$InstanceInfoBuilderImpl.class
|
||||
com\muyu\test\fluxmqTest.class
|
||||
com\muyu\common\domain\InstanceInfo.class
|
||||
com\muyu\controller\AlController.class
|
||||
com\muyu\controller\WorkGetWayNode.class
|
||||
com\muyu\common\domain\CreateVo.class
|
||||
com\muyu\common\domain\Icreate$IcreateBuilderImpl.class
|
||||
com\muyu\demos\web\User.class
|
||||
com\muyu\common\config\RedisConfig.class
|
||||
com\muyu\common\aly\AliYunRcsService.class
|
||||
com\muyu\common\domain\NodeRegReq$NodeRegReqBuilder.class
|
||||
com\muyu\demos\web\PathVariableController.class
|
||||
com\muyu\common\domain\DeleteServer.class
|
||||
com\muyu\common\domain\MqttInfo.class
|
||||
com\muyu\common\utils\Result$ResultBuilder.class
|
||||
com\muyu\common\domain\JVMInfo.class
|
||||
com\muyu\common\config\AliConfig.class
|
||||
com\muyu\common\config\ClientConfig.class
|
||||
com\muyu\common\contents\CreateContents.class
|
||||
com\muyu\common\domain\ApifoxModel.class
|
||||
com\muyu\common\domain\IsanJoin$IsanJoinBuilderImpl.class
|
||||
com\muyu\controller\stiNode.class
|
||||
com\muyu\common\domain\Icreate$IcreateBuilder.class
|
||||
com\muyu\common\utils\Result.class
|
||||
com\muyu\common\domain\CreateVo$CreateVoBuilder.class
|
||||
com\muyu\demos\web\BasicController.class
|
||||
com\muyu\common\domain\CPUInfo.class
|
||||
com\muyu\common\domain\InstanceInfo$InstanceInfoBuilder.class
|
||||
com\muyu\common\config\CreateAnConfig.class
|
||||
com\muyu\server\NodeRegReq$NodeRegReqBuilder.class
|
||||
com\muyu\common\domain\Icreate.class
|
||||
com\muyu\common\domain\FlowInfo.class
|
||||
com\muyu\common\domain\DeleteServer$DeleteServerBuilder.class
|
||||
com\muyu\controller\VehicleController.class
|
|
@ -0,0 +1,30 @@
|
|||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\controller\VehicleController.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\demos\web\User.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\DeleteServer.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\MqttInfo.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\demos\web\BasicController.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\utils\Result.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\test\fluxmqTest.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\ApifoxModel.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\config\AliConfig.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\config\CreateAnConfig.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\redis\RedisService.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\controller\LoadCenterController.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\config\ClientConfig.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\config\FastJson2JsonRedisSerializer.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\aly\AliYunRcsService.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\Icreate.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\JVMInfo.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\CPUInfo.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\controller\AlController.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\IsanJoin.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\contents\CreateContents.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\Ynpplication.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\FlowInfo.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\NodeRegReq.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\CreateVo.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\demos\web\PathVariableController.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\domain\InstanceInfo.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\common\config\RedisConfig.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\server\NodeRegReq.java
|
||||
C:\Users\yn\Desktop\acb\src\main\java\com\muyu\server\ClientRegController.java
|
|
@ -0,0 +1 @@
|
|||
com\muyu\MqttApplicationTests.class
|
|
@ -0,0 +1 @@
|
|||
C:\Users\yn\Desktop\acb\src\test\java\com\muyu\MqttApplicationTests.java
|
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,4 @@
|
|||
-------------------------------------------------------------------------------
|
||||
Test set: com.muyu.MqttApplicationTests
|
||||
-------------------------------------------------------------------------------
|
||||
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.485 s - in com.muyu.MqttApplicationTests
|
Binary file not shown.
Loading…
Reference in New Issue