第一次修改代码

master
liuyunhu 2024-04-17 09:35:41 +08:00
parent 396742ce64
commit 71143d6fc5
17 changed files with 698 additions and 435 deletions

View File

@ -2,7 +2,6 @@ package com.lyh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @ProjectName: Default (Template) Project
@ -12,7 +11,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
*/
@SpringBootApplication
@EnableScheduling
//@EnableScheduling
//@EnableFeignClients
public class LoadCenterApplication {
public static void main(String[] args) {

View File

@ -0,0 +1,367 @@
package com.lyh.common.aliyun;
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.lyh.common.aliyun.model.InstanceSpecification;
import com.lyh.common.config.AliConfig;
import com.lyh.common.domain.InstancesInformation;
import com.lyh.common.redis.service.RedisService;
import com.lyh.common.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/16
* @Description: ecsopenAPI
*/
@Component
@Slf4j
public class AliYunEcsService {
/*
*,
* */
@Autowired
private InstanceSpecification instanceSpecification;
//应用阿里云客户端配置
private final AliConfig aliConfig;
private final Client client;
public AliYunEcsService(AliConfig aliConfig, Client client) {
this.aliConfig = aliConfig;
this.client = client;
}
/*
* redis
* */
@Autowired
private RedisService redisService;
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 20:01
* @Description: ID
* @Param: []
* @Return: java.util.List<java.lang.String>
**/
public List<String> getIDList() throws Exception {
java.util.List<String> regionIds = com.aliyun.darabonbastring.Client.split(aliConfig.getRegionId(), ",", 50);
String regionId = regionIds.get(0);
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
.setPageSize(100)
.setRegionId(regionId);
DescribeInstancesResponse resp = this.client.describeInstances(describeInstancesRequest);
java.util.List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instances = resp.body.instances.instance;
com.aliyun.teaconsole.Client.log(regionId + " 下 ECS 实例列表:");
//存储结果的List
ArrayList<String> result = new ArrayList<>();
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : instances) {
com.aliyun.teaconsole.Client.log("主机名:" + instance.hostName + " 实例ID" + instance.instanceId + " CPU" + instance.cpu + " 内存:" + instance.memory + " MB 规格:" + instance.instanceType + " 系统:" + instance.OSType + "(" + instance.OSName + ") 状态:" + instance.status);
result.add(instance.instanceId);
}
//将查询到的ecs服务器id列表 打印控制台
log.info(JSON.toJSONString(result));
//返回结果
return result;
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 20:19
* @Description: ID ID
* @Param: instanceIds ID
* @Return:
**/
public void releaseInstances(String instanceIds) throws Exception {
// 实例名称,支持使用通配符*进行模糊搜索
String instanceName = "*";
// 强制删除有删除保护的机器
String deleteProtected = "true";
// 强制删除运行中的机器
String force = "true";
//判断是否为强制删除
if (Common.equalString(deleteProtected, "true")) {
DescribeInstancesResponse describeInstancesResp = DescribeInstances(client, aliConfig.getRegionId(), 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 (Common.empty(instanceIds)) {
com.aliyun.teaconsole.Client.log("--------------------无有效实例可删除--------------------");
return;
}
DeleteInstances(client, aliConfig.getRegionId(), instanceIds, force);
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 20:31
* @Description:
* @Param: [client, regionId, instanceIds, instanceName]
* @Return: DescribeInstancesResponse
**/
public static DescribeInstancesResponse DescribeInstances(Client client, String regionId, String instanceIds, String instanceName) throws Exception {
DescribeInstancesRequest req = new DescribeInstancesRequest()
.setRegionId(regionId)
.setInstanceName(instanceName);
if (!Common.empty(instanceIds)) {
req.instanceIds = Common.toJSONString(com.aliyun.darabonbastring.Client.split(instanceIds, ",", 50));
}
DescribeInstancesResponse resp = client.describeInstances(req);
com.aliyun.teaconsole.Client.log("--------------------查询需要删除的实例--------------------");
return resp;
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 20:33
* @Description:
* @Param: [client, instatnceId]
* @Return: void
**/
public static void ModifyInstanceAttribute(Client client, String instatnceId) throws Exception {
ModifyInstanceAttributeRequest req = new ModifyInstanceAttributeRequest()
.setInstanceId(instatnceId)
.setDeletionProtection(false);//设置删除保护为false
client.modifyInstanceAttribute(req);
com.aliyun.teaconsole.Client.log("--------------------" + instatnceId + "释放保护取消成功--------------------");
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 20:35
* @Description:
* @Param: [client, regionId, instanceIds, force]
* @Return: void
**/
public static void DeleteInstances(com.aliyun.ecs20140526.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(Common.equalString(force, "true"));
DeleteInstancesResponse resp = client.deleteInstances(req);
com.aliyun.teaconsole.Client.log("--------------------实例释放成功--------------------");
com.aliyun.teaconsole.Client.log(Common.toJSONString(Common.toMap(resp)));
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 21:44
* @Description:
* @Param: []
* @Return: java.lang.String
**/
public String createAndRunInstance() throws Exception {
//获取实例规格
// 地域Id
String regionId = aliConfig.getRegionId();
// 镜像 ID启动实例时选择的镜像资源。
String imageId = instanceSpecification.getImageId();
// 实例规格
String instanceType = instanceSpecification.getInstanceType();
// 新创建实例所属于的安全组 ID。
String securityGroupId = instanceSpecification.getSecurityGroupId();
// 虚拟交换机 ID。
String vSwitchId = instanceSpecification.getVSwitchId();
// 公网出带宽最大值,单位为 Mbit/s。取值范围0~100。 默认值0。
Integer internetMaxBandwidthOut = com.aliyun.darabonbanumber.Client.parseInt(instanceSpecification.getInternetMaxBandwidthOut());
// 网络计费类型。取值范围:
// PayByBandwidth: 按固定带宽计费。
// PayByTraffic: 按使用流量计费。
// 默认值PayByTraffic。
String internetChargeType = instanceSpecification.getInternetChargeType();
// 系统盘大小
String size = instanceSpecification.getSize();
// 系统盘的云盘种类
String category = instanceSpecification.getCategory();
// ECS实例的计费方式
// PrePaid包年包月
// PostPaid按量付费
String instanceChargeType = instanceSpecification.getInstanceChargeType();
// 批量创建实例
return RunInstances(client, regionId, imageId, instanceType, securityGroupId, vSwitchId, internetMaxBandwidthOut, internetChargeType, size, category, instanceChargeType);
}
/**
* RunInstances ECS
* RunInstancesECSDescribeRecommendInstanceTypeECS
*/
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 {
RunInstancesRequest request = new RunInstancesRequest()
.setRegionId(regionId)
.setImageId(imageId)
.setInstanceType(instanceType)
.setSecurityGroupId(securityGroupId)
.setVSwitchId(vSwitchId)
.setInstanceName("自动创建的实例节点")
.setDescription(new Date().toLocaleString() + " 创建的实例节点")
.setInternetMaxBandwidthOut(internetMaxBandwidthOut)
.setInternetChargeType(internetChargeType)
.setInstanceChargeType(instanceChargeType)
// 批量创建五台ECS实例如果不设置该参数默认创建一台ECS实例。
// amount = 5,
// 如果缺少库存可以接受的最低创建数量。
// minAmount = 2,
// 打开预检参数功能不会实际创建ECS实例只检查参数正确性、用户权限或者ECS库存等问题。
// 实际情况下设置了DryRun参数后Amount必须为1MinAmount必须为空您可以根据实际需求修改代码。
// .setDryRun(true)
.setDryRun(false)
.setSystemDisk(new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setSize(size)
.setCategory(category));
String result = "";
try {
com.aliyun.teaconsole.Client.log("--------------------批量创建实例开始--------------------");
RunInstancesResponse responces = client.runInstances(request);
com.aliyun.teaconsole.Client.log("--------------------创建实例成功实例ID:" + Common.toJSONString(responces.body.instanceIdSets.instanceIdSet) + "--------------------");
//返回实例ID
result = responces.body.instanceIdSets.instanceIdSet + "";//前后带 []
result = UserUtil.removeBrackets(result);//前后不带[]
} catch (TeaException error) {
com.aliyun.teaconsole.Client.log("--------------------创建实例失败:" + Common.toJSONString(error.code) + "--------------------" + error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
com.aliyun.teaconsole.Client.log("--------------------创建实例失败:" + Common.toJSONString(error.code) + "--------------------" + error.message);
}
return result;
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 22:02
* @Description:
* @Param: [instanceIds] i-uf6chlqotgoc9h173alu
**/
public List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> queryInstancesInformation(String instanceIds) throws Exception {
//初始化计数器
AtomicInteger count = new AtomicInteger();
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
.setRegionId(aliConfig.getRegionId())
.setInstanceName("*")
.setInstanceIds(Common.toJSONString(com.aliyun.darabonbastring.Client.split(instanceIds, ",", 50)))
.setPageSize(10);
RuntimeOptions runtime = new RuntimeOptions();
//初始化返回值
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instances = null;
try {
// 复制代码运行请自行打印 API 的返回值
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances bodyInstances = describeInstancesResponse.getBody().getInstances();
//
instances = bodyInstances.getInstance();
//新建List用于redis存储实例信息
ArrayList<InstancesInformation> instancesInformations = new ArrayList<>();
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance item : instances) {
log.info("查询第{" + count.get() + 1 + "}个实例的ID:" + item.getInstanceId());
log.info("名称:" + item.getInstanceName());
log.info("地域ID:" + item.getRegionId());
log.info("状态:" + item.getStatus());
log.info("类型:" + item.getInstanceType());
log.info("CPU核心数:" + item.getCpu());
log.info("内存大小:" + item.getMemory() + "MB");
log.info("磁盘大小:" + item.getLocalStorageCapacity() + "G");
log.info("操作系统:" + item.getOSName());
log.info("网络类型:" + item.getInstanceNetworkType());
log.info("公网出带宽值:" + item.getInternetMaxBandwidthOut() + "Mbit/s");
log.info("公网入带宽值:" + item.getInternetMaxBandwidthIn() + "Mbit/s");
log.info("公网IP:" + UserUtil.removeBrackets(item.getPublicIpAddress().getIpAddress().toString()));
log.info("私网IP:" + UserUtil.removeBrackets(item.getVpcAttributes().getPrivateIpAddress().ipAddress.toString()));
log.info("专有网络VPCID:" + item.getVpcAttributes().getVpcId());
log.info("安全组ID:" + UserUtil.removeBrackets(item.getSecurityGroupIds().getSecurityGroupId().toString()));
log.info("创建时间:" + item.getCreationTime());
log.info("到期时间:" + item.getExpiredTime());
log.info("是否可以回收:" + (item.getRecyclable() ? "是" : "否") + "\n\n");
//存入集合
instancesInformations.add(
new InstancesInformation(
item.getInstanceId(),
item.getInstanceName(),
item.getStatus(),
UserUtil.removeBrackets(item.getPublicIpAddress().getIpAddress().toString()),
UserUtil.removeBrackets(item.getVpcAttributes().getPrivateIpAddress().ipAddress.toString()),
item.getCreationTime(),
item.getExpiredTime(),
item.getRecyclable()
)
);
count.getAndIncrement();
}
//缓存数据
redisService.deleteObject("服务器信息:");
redisService.setCacheList("服务器信息:", instancesInformations);
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
log.error(error.getMessage());
// 诊断地址
log.error(error.getData().get("Recommend").toString());
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
log.error(error.getMessage());
// 诊断地址
log.error(error.getData().get("Recommend").toString());
Common.assertAsString(error.message);
}
return instances;
}
}

View File

@ -0,0 +1,77 @@
package com.lyh.common.aliyun.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/16
* @Description:
*/
@Configuration
@ConfigurationProperties(prefix = "config.instance")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class InstanceSpecification {
/*
* ID
* */
private String imageId;
/*
*
* */
private String instanceType;
/*
* ID
* */
private String securityGroupId;
/*
* ID
* */
private String vSwitchId;
/*
* Mbit/s0~100 0
* */
private String internetMaxBandwidthOut;
/*
*
* PayByBandwidth:
* PayByTraffic: 使
* PayByTraffic
* */
private String internetChargeType;
/*
*
* */
private String size;
/*
*
* */
private String category;
/*
*ECS
* PrePaid
* PostPaid
* */
private String instanceChargeType;
}

View File

@ -0,0 +1,61 @@
package com.lyh.common.config;
import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/16
* @Description:
*/
@Configuration
@ConfigurationProperties(prefix = "config.aliyun")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AliConfig {
/*
* access-key-id
* */
private String accessKeyId;
/*
* access-key-secret
* */
private String accessKeySecret;
/*
* id
* */
private String regionId;
/*
* @Author: LiuYunHu
* @Date: 2024/4/16 21:29
* @Description:
* @Param: [aliConfig]
* @Return: com.aliyun.ecs20140526.Client
**/
@Bean
public Client createEcsClient(AliConfig aliConfig) throws Exception {
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId(aliConfig.accessKeyId)
// 您的AccessKey Secret
.setAccessKeySecret(aliConfig.accessKeySecret)
// 您的可用区ID
.setRegionId(aliConfig.regionId);
// // 设置连接超时为5000毫秒
// .setConnectTimeout(5000)
// // 设置读超时为5000毫秒
// .setReadTimeout(5000);
return new Client(config);
}
}

View File

@ -1,39 +0,0 @@
package com.lyh.common.config;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.stereotype.Component;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/13
* @Description:
*/
@Component
public class ClientService {
/*
* @Author: LiuYunHu
* @Date: 2024/4/13 9:52
* @Description:
* @Param:
* @Return:
**/
public static com.aliyun.ecs20140526.Client createEcsClient(String regionId) throws Exception {
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId("LTAI5tEBb3cjLf8nRBJZmfD9")
// 您的AccessKey Secret
.setAccessKeySecret("Emzjl8SlqwlHP7xeFOrhwtXiJNfbkF")
// 您的可用区ID
.setRegionId(regionId)
// 设置连接超时为5000毫秒
.setConnectTimeout(5000)
// 设置读超时为5000毫秒
.setReadTimeout(5000);
return new com.aliyun.ecs20140526.Client(config);
}
}

View File

@ -0,0 +1,69 @@
package com.lyh.common.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/16
* @Description:
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class InstancesInformation {
/*
* log.info("查询第{" + count + "}个实例的ID:" + item.getInstanceId());
log.info("名称:" + item.getInstanceName());
log.info("状态:" + item.getStatus());
log.info("公网IP:" + UserUtil.removeBrackets(item.getPublicIpAddress().getIpAddress().toString()));
log.info("私网IP:" + UserUtil.removeBrackets(item.getVpcAttributes().getPrivateIpAddress().ipAddress.toString()));
log.info("创建时间:" + item.getCreationTime());
log.info("到期时间:" + item.getExpiredTime());
log.info("是否可以回收:" + (item.getRecyclable() ? "是" : "否") + "\n\n");
* */
/*
* ID
* */
private String instanceId;
/*
*
* */
private String instanceName;
/*
*
* */
private String status;
/*
* IP
* */
private String publicIpAddress;
/*
* IP
* */
private String privateIpAddress;
/*
*
* */
private String creationTime;
/*
*
* */
private String expiredTime;
/*
*
* */
private Boolean recyclable;
}

View File

@ -2,7 +2,7 @@ package com.lyh.common.utils.mqtt;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@ -18,7 +18,7 @@ import java.io.IOException;
*/
@Component
@Log4j2
@Slf4j
public class MqttUtil {
/*

View File

@ -2,7 +2,6 @@ package com.lyh.controller;
import com.lyh.common.domain.resp.Result;
import com.lyh.service.LoadCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -17,7 +16,6 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/loadCenter")
@Slf4j
public class LoadCenterController {
@Autowired
private LoadCenterService loadCenterService;

View File

@ -2,11 +2,12 @@ package com.lyh.job;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.lyh.openAPI.WorkCenter.CreateAndRunInstance;
import com.lyh.common.aliyun.AliYunEcsService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
@ -18,6 +19,14 @@ import org.springframework.stereotype.Component;
@Component
@Slf4j
public class Timer {
/*
* api
* */
@Autowired
private AliYunEcsService aliYunEcsService;
// @Scheduled(cron = "0/10 * * * * ?")
public void test() {
String ip = "47.102.123.209";
@ -53,7 +62,7 @@ public class Timer {
//执行节点扩容
//返回实例的ID
String instanceId = CreateAndRunInstance.startCreate();
String instanceId = aliYunEcsService.createAndRunInstance();
if (!instanceId.isEmpty()) {
log.info("扩容 成功!");
@ -62,7 +71,7 @@ public class Timer {
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}

View File

@ -1,105 +0,0 @@
// This file is auto-generated, don't edit it. Thanks.
package com.lyh.openAPI.WorkCenter;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import com.aliyun.ecs20140526.models.RunInstancesResponse;
import com.aliyun.tea.TeaException;
import com.lyh.common.config.ClientService;
import com.lyh.common.utils.UserUtil;
import org.springframework.stereotype.Component;
import java.util.Date;
/*
*
* */
@Component
public class CreateAndRunInstance {
/*
* @Author: LiuYunHu
* @Date: 2024/4/13 9:28
* @Description:
* @Param: []
* @Return: java.lang.String
**/
public static String startCreate() throws Exception {
// 地域Id
String regionId = "cn-shanghai";
// 镜像 ID启动实例时选择的镜像资源。
String imageId = "m-uf63t8i01vefni8piwen";
// 实例规格
String instanceType = "ecs.e-c1m1.large";
// 新创建实例所属于的安全组 ID。
String securityGroupId = "sg-uf6fvbhimn7xa54i36wc";
// 虚拟交换机 ID。
String vSwitchId = "vsw-uf62esxo4f5dfs43aqfu6";
// 公网出带宽最大值,单位为 Mbit/s。取值范围0~100。 默认值0。
Integer internetMaxBandwidthOut = com.aliyun.darabonbanumber.Client.parseInt("5");
// 网络计费类型。取值范围:
// PayByBandwidth: 按固定带宽计费。
// PayByTraffic: 按使用流量计费。
// 默认值PayByTraffic。
String internetChargeType = "PayByTraffic";
// 系统盘大小
String size = "20";
// 系统盘的云盘种类
String category = "cloud_essd_entry";
// ECS实例的计费方式
// PrePaid包年包月
// PostPaid按量付费
String instanceChargeType = "PostPaid";
com.aliyun.ecs20140526.Client client = ClientService.createEcsClient(regionId);
// 批量创建实例
return CreateAndRunInstance.RunInstances(client, regionId, imageId, instanceType, securityGroupId, vSwitchId, internetMaxBandwidthOut, internetChargeType, size, category, instanceChargeType);
}
/**
* RunInstances ECS
* RunInstancesECSDescribeRecommendInstanceTypeECS
*/
public static String RunInstances(com.aliyun.ecs20140526.Client client, String regionId, String imageId, String instanceType, String securityGroupId, String vSwitchId, Integer internetMaxBandwidthOut, String internetChargeType, String size, String category, String instanceChargeType) throws Exception {
RunInstancesRequest request1 = new RunInstancesRequest()
.setRegionId(regionId)
.setImageId(imageId)
.setInstanceType(instanceType)
.setSecurityGroupId(securityGroupId)
.setVSwitchId(vSwitchId)
.setInstanceName("自动创建的实例节点")
.setDescription(new Date().toLocaleString() + " 创建的实例节点")
.setInternetMaxBandwidthOut(internetMaxBandwidthOut)
.setInternetChargeType(internetChargeType)
.setInstanceChargeType(instanceChargeType)
// 批量创建五台ECS实例如果不设置该参数默认创建一台ECS实例。
// amount = 5,
// 如果缺少库存可以接受的最低创建数量。
// minAmount = 2,
// 打开预检参数功能不会实际创建ECS实例只检查参数正确性、用户权限或者ECS库存等问题。
// 实际情况下设置了DryRun参数后Amount必须为1MinAmount必须为空您可以根据实际需求修改代码。
// .setDryRun(true)
.setDryRun(false)
.setSystemDisk(new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setSize(size)
.setCategory(category));
String result = "";
try {
com.aliyun.teaconsole.Client.log("--------------------批量创建实例开始--------------------");
RunInstancesResponse responces = client.runInstances(request1);
com.aliyun.teaconsole.Client.log("--------------------创建实例成功实例ID:" + com.aliyun.teautil.Common.toJSONString(responces.body.instanceIdSets.instanceIdSet) + "--------------------");
//返回实例ID
result = responces.body.instanceIdSets.instanceIdSet + "";//前后带 []
result = UserUtil.removeBrackets(result);//前后不带[]
} catch (TeaException error) {
com.aliyun.teaconsole.Client.log("--------------------创建实例失败:" + com.aliyun.teautil.Common.toJSONString(error.code) + "--------------------" + error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
com.aliyun.teaconsole.Client.log("--------------------创建实例失败:" + com.aliyun.teautil.Common.toJSONString(error.code) + "--------------------" + error.message);
}
return result;
}
}

View File

@ -1,68 +0,0 @@
package com.lyh.openAPI.WorkCenter;
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.lyh.common.config.ClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/15
* @Description: ID
*/
@Component
@Slf4j
public class GetInstanceIDList {
public static List<String> getIDList() throws Exception {
// // 1. 初始化配置
// Config config = new Config();
// // 您的AccessKey ID
// config.accessKeyId = "LTAI5tEBb3cjLf8nRBJZmfD9";
// // 您的AccessKey Secret
// config.accessKeySecret = "Emzjl8SlqwlHP7xeFOrhwtXiJNfbkF";
// //设置请求地址
// config.endpoint = "ecs.aliyuncs.com";
// // 设置连接超时为5000毫秒
// config.connectTimeout = 5000;
// // 设置读超时为5000毫秒
// config.readTimeout = 5000;
// // 2. 初始化客户端
// com.aliyun.ecs20140526.Client client = new com.aliyun.ecs20140526.Client(config);
// 地域Id
String addressId = "cn-shanghai";
Client client = ClientService.createEcsClient(addressId);
java.util.List<String> regionIds = com.aliyun.darabonbastring.Client.split(addressId, ",", 50);
String regionId = regionIds.get(0);
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest()
.setPageSize(100)
.setRegionId(regionId);
DescribeInstancesResponse resp = client.describeInstances(describeInstancesRequest);
java.util.List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instances = resp.body.instances.instance;
com.aliyun.teaconsole.Client.log("" + regionId + " 下 ECS 实例列表:");
//存储结果的List
ArrayList<String> result = new ArrayList<>();
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : instances) {
com.aliyun.teaconsole.Client.log("主机名:" + instance.hostName + " 实例ID" + instance.instanceId + " CPU" + instance.cpu + " 内存:" + instance.memory + " MB 规格:" + instance.instanceType + " 系统:" + instance.OSType + "(" + instance.OSName + ") 状态:" + instance.status + "");
result.add(instance.instanceId);
}
log.info(result);
//返回结果
return result;
}
}

View File

@ -1,98 +0,0 @@
package com.lyh.openAPI.WorkCenter;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.aliyun.tea.TeaException;
import com.lyh.common.config.ClientService;
import com.lyh.common.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @ProjectName: LoadCenter
* @Author: LiuYunHu
* @CreateTime: 2024/4/13
* @Description: ECS
*/
@Component
@Slf4j
public class GetInstanceProperties {
static int i = 1;
/*
* @Author: LiuYunHu
* @Date: 2024/4/13 11:01
* @Description: ID
* @Param: [instanceIds] i-uf6chlqotgoc9h173alu
* @Return: void
**/
public static List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> startGet(String instanceIds) throws Exception {
// 地域Id
String regionId = "cn-shanghai";
com.aliyun.ecs20140526.Client client = ClientService.createEcsClient(regionId);
com.aliyun.ecs20140526.models.DescribeInstancesRequest describeInstancesRequest = new com.aliyun.ecs20140526.models.DescribeInstancesRequest()
.setRegionId(regionId)
.setInstanceName("*")
.setInstanceIds(com.aliyun.teautil.Common.toJSONString(com.aliyun.darabonbastring.Client.split(instanceIds, ",", 50)))
.setPageSize(10);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
//初始化返回值
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> instance = null;
try {
// 复制代码运行请自行打印 API 的返回值
DescribeInstancesResponse describeInstancesResponse = client.describeInstancesWithOptions(describeInstancesRequest, runtime);
DescribeInstancesResponseBody body = describeInstancesResponse.getBody();
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstances instances = body.getInstances();
//能返回的值
instance = instances.getInstance();
instance.forEach(item -> {
log.info("实例{" + i + "}的ID:" + item.getInstanceId());
log.info("名称:" + item.getInstanceName());
log.info("地域ID:" + item.getRegionId());
log.info("状态:" + item.getStatus());
log.info("类型:" + item.getInstanceType());
log.info("CPU核心数:" + item.getCpu());
log.info("内存大小:" + item.getMemory() + "MB");
log.info("磁盘大小:" + item.getLocalStorageCapacity() + "G");
log.info("操作系统:" + item.getOSName());
log.info("网络类型:" + item.getInstanceNetworkType());
log.info("公网出带宽值:" + item.getInternetMaxBandwidthOut() + "Mbit/s");
log.info("公网入带宽值:" + item.getInternetMaxBandwidthIn() + "Mbit/s");
log.info("公网IP:" + UserUtil.removeBrackets(item.getPublicIpAddress().getIpAddress().toString()));
log.info("私网IP:" + UserUtil.removeBrackets(item.getVpcAttributes().getPrivateIpAddress().ipAddress.toString()));
log.info("专有网络VPCID:" + item.getVpcAttributes().getVpcId());
log.info("安全组ID:" + UserUtil.removeBrackets(item.getSecurityGroupIds().getSecurityGroupId().toString()));
log.info("创建时间:" + item.getCreationTime());
log.info("到期时间:" + item.getExpiredTime());
log.info("是否可以回收:" + (item.getRecyclable() ? "是" : "否") + "\n\n");
log.info("---------------------");
i++;
});
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
log.error(error.getMessage());
// 诊断地址
log.error(error.getData().get("Recommend").toString());
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
log.error(error.getMessage());
// 诊断地址
log.error(error.getData().get("Recommend").toString());
com.aliyun.teautil.Common.assertAsString(error.message);
}
return instance;
}
}

View File

@ -1,85 +0,0 @@
// This file is auto-generated, don't edit it. Thanks.
package com.lyh.openAPI.WorkCenter;
import com.aliyun.ecs20140526.models.*;
import com.lyh.common.config.ClientService;
import org.springframework.stereotype.Component;
/**
* @ProjectName: five-groups-couplet
* @Author: LiuYunHu
* @CreateTime: 2024/4/12
* @Description:
*/
@Component
public class ReleaseInstance {
public static DescribeInstancesResponse DescribeInstances(com.aliyun.ecs20140526.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(com.aliyun.ecs20140526.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(com.aliyun.ecs20140526.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)));
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/13 11:02
* @Description: ID
* @Param: [instanceIds] i-uf6chlqotgoc9h173alu
* @Return: void
**/
public static void startRelease(String instanceIds) throws Exception {
// 区域ID
String regionId = "cn-shanghai";
// 实例名称,支持使用通配符*进行模糊搜索
String instanceName = "*";
// 强制删除有删除保护的机器
String deleteProtected = "true";
// 强制删除运行中的机器
String force = "true";
com.aliyun.ecs20140526.Client client = ClientService.createEcsClient(regionId);
if (com.aliyun.teautil.Common.equalString(deleteProtected, "true")) {
DescribeInstancesResponse describeInstancesResp = ReleaseInstance.DescribeInstances(client, regionId, instanceIds, instanceName);
instanceIds = "";
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance instance : describeInstancesResp.body.instances.instance) {
instanceIds = "" + instance.instanceId + "," + instanceIds + "";
if (instance.deletionProtection) {
ReleaseInstance.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;
}
ReleaseInstance.DeleteInstances(client, regionId, instanceIds, force);
}
}

View File

@ -1,16 +1,16 @@
package com.lyh.service.impl;
import com.alibaba.fastjson2.JSON;
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.lyh.common.aliyun.AliYunEcsService;
import com.lyh.common.domain.IpAndLoadCount;
import com.lyh.common.domain.IpAndWeight;
import com.lyh.common.domain.resp.Result;
import com.lyh.common.redis.service.RedisService;
import com.lyh.common.utils.UserUtil;
import com.lyh.common.utils.mqtt.MqttUtil;
import com.lyh.openAPI.WorkCenter.GetInstanceIDList;
import com.lyh.openAPI.WorkCenter.GetInstanceProperties;
import com.lyh.service.LoadCenterService;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -24,7 +24,7 @@ import java.util.List;
* @Description:
*/
@Service
@Log4j2
@Slf4j
public class LoadCenterServiceImpl implements LoadCenterService {
@Autowired
private MqttUtil mqttUtil;
@ -32,6 +32,9 @@ public class LoadCenterServiceImpl implements LoadCenterService {
@Autowired
private RedisService redis;
@Autowired
private AliYunEcsService aliYunEcsService;
/*
* @Author: LiuYunHu
* @Date: 2024/4/15 21:49
@ -47,11 +50,12 @@ public class LoadCenterServiceImpl implements LoadCenterService {
//获取上海区的实例ID列表
try {
List<String> idList = GetInstanceIDList.getIDList();
List<String> idList = aliYunEcsService.getIDList();
idList.forEach(id -> {
//调用方法获取对应ID实例的IP
try {
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> result = GetInstanceProperties.startGet(id);
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> result = aliYunEcsService.queryInstancesInformation(id);
//获取集合第一个的属性
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance response = result.get(0);
@ -68,7 +72,7 @@ public class LoadCenterServiceImpl implements LoadCenterService {
log.error(e.getMessage());
}
log.info(ipList);
log.info(JSON.toJSONString(ipList));
//将IP列表存入redis
redis.deleteObject("服务器列表:");
@ -87,7 +91,7 @@ public class LoadCenterServiceImpl implements LoadCenterService {
//求出空负载的总量
Integer emptyLoadCount = 0;
int emptyLoadCount = 0;
for (IpAndLoadCount ipAndLoadCount : ipAndLoadCounts) {
//假设使用2/8原则
@ -103,7 +107,7 @@ public class LoadCenterServiceImpl implements LoadCenterService {
ipAndWeights.add(ipAndWeight);
}
log.info(ipAndWeights);//[IpAndWeight(nodeIp=47.102.158.233, weight=55), IpAndWeight(nodeIp=47.102.123.209, weight=44)]
log.info(JSON.toJSONString(ipAndWeights));//[IpAndWeight(nodeIp=47.102.158.233, weight=55), IpAndWeight(nodeIp=47.102.123.209, weight=44)]
//*******************************************以下为改老师的代码
@ -144,7 +148,6 @@ public class LoadCenterServiceImpl implements LoadCenterService {
redis.setCacheList("work:node:gateway", loadNodeList);
//获取缓存里最后一个IP进行返回
//最后一个IP进行返回
String result = loadNodeList.get(loadNodeList.size() - 1);

View File

@ -8,6 +8,49 @@ spring:
host: 127.0.0.1
port: 6379
config:
aliyun:
access-key-id: LTAI5tEBb3cjLf8nRBJZmfD9
access-key-secret: Emzjl8SlqwlHP7xeFOrhwtXiJNfbkF
region-id: cn-shanghai
instance:
#镜像ID
image-id: m-uf63t8i01vefni8piwen
#实例规格
instance-type: ecs.e-c1m1.large
#新创建实例所属于的安全组 ID
security-group-id: sg-uf6fvbhimn7xa54i36wc
#虚拟交换机 ID
v-switch-id: vsw-uf62esxo4f5dfs43aqfu6
#公网出带宽最大值,单位为 Mbit/s。取值范围0~100。 默认值0
internet-max-bandwidth-out: 5
#网络计费类型。取值范围:
#PayByBandwidth: 按固定带宽计费。
#PayByTraffic: 按使用流量计费。
#默认值PayByTraffic。
internet-charge-type: PayByTraffic
#系统盘大小
size: 20
#系统盘的云盘种类
#cloud普通云盘
#cloud_efficiency高效云盘
#cloud_ssdSSD 云盘
#cloud_essdESSD 云盘
#cloud_autoESSD AutoPL 云盘
#cloud_essd_entryESSD Entry 云盘
category: cloud_essd_entry
#ECS实例的计费方式
#PrePaid包年包月
#PostPaid按量付费
instance-charge-type: PostPaid

View File

@ -1,9 +1,10 @@
import com.alibaba.fastjson2.JSON;
import com.lyh.LoadCenterApplication;
import com.lyh.common.redis.service.RedisService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@ -22,7 +23,7 @@ import java.util.concurrent.CountDownLatch;
*/
@SpringBootTest(classes = LoadCenterApplication.class)
@Log4j2
@Slf4j
public class LoadTest {
@Autowired
private RedisService redisService;
@ -135,9 +136,9 @@ public class LoadTest {
// log.info(cursor + "---" + nodeId);
// }
log.info(nodeIdList);
log.info(JSON.toJSONString(nodeIdList));
log.info(loadNodeList);
log.info(JSON.toJSONString(loadNodeList));
}
@ -145,7 +146,7 @@ public class LoadTest {
}
@Log4j2
@Slf4j
class stiNode {
private static Map<String, Integer> stiNodeMap = new HashMap<>();
@ -155,14 +156,13 @@ class stiNode {
}
public static void show() {
stiNodeMap.forEach((key,val)->{
log.info(key+"----"+val);
stiNodeMap.forEach((key, val) -> {
log.info(key + "----" + val);
});
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor

View File

@ -1,9 +1,8 @@
import com.aliyun.ecs20140526.models.DescribeInstancesResponseBody;
import com.lyh.LoadCenterApplication;
import com.lyh.common.aliyun.AliYunEcsService;
import com.lyh.common.redis.service.RedisService;
import com.lyh.common.utils.UserUtil;
import com.lyh.openAPI.WorkCenter.GetInstanceProperties;
import com.lyh.openAPI.WorkCenter.ReleaseInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@ -23,28 +22,43 @@ import java.util.List;
public class Test {
@Autowired
private RedisService redisService;
@Autowired
private AliYunEcsService aliYunEcsService;
/*
* @Author: LiuYunHu
* @Date: 2024/4/17 9:19
* @Description: ID
* @Param: []
* @Return: void
**/
@org.junit.jupiter.api.Test
public void load() throws Exception {
public void queryInstancesInformation() throws Exception {
// //返回实例的ID
// String instanceId = CreateAndRunInstance.startCreate();
//
// Thread.sleep(2000);
String instanceId = "i-uf6chlqotgoc9h173alu";
String instanceId = "i-uf6if4mw6iu6rjffrs2c,i-uf6a4lwh3qdqwa5t5237";
//通过实例ID获取实例的详细属性
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> describeInstancesResponseBodyInstancesInstances = GetInstanceProperties.startGet(instanceId);
//通过实例ID获取实例的详细属性 多个实例用英文逗号隔开
List<DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance> describeInstancesResponseBodyInstancesInstances = aliYunEcsService.queryInstancesInformation(instanceId);
describeInstancesResponseBodyInstancesInstances.forEach(item->{
//循环打印所有的实例IP
log.info(UserUtil.removeBrackets(item.getPublicIpAddress().getIpAddress().toString()));
});
//获取集合第一个的属性
DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance response = describeInstancesResponseBodyInstancesInstances.get(0);
//获取添加的实例的公网ip
String instanceIp = UserUtil.removeBrackets(response.getPublicIpAddress().getIpAddress().toString());
System.out.println("-----------------------");
log.info(instanceIp);
System.out.println("-----------------------");
log.info("-----------------------");
log.info("第一个实例的公网IP为"+instanceIp);
log.info("-----------------------");
}
@ -53,11 +67,29 @@ public class Test {
/*
*
* */
* @Author: LiuYunHu
* @Date: 2024/4/17 9:19
* @Description:
* @Param: []
* @Return: void
**/
@org.junit.jupiter.api.Test
public void aaa() throws Exception {
ReleaseInstance.startRelease("i-uf660jbffjg2mrrs4h91,i-uf6dac58ernhfgpjn6nn");
public void releaseInstances() throws Exception {
aliYunEcsService.releaseInstances("i-uf6if4mw6iu6rjffrs2c,i-uf6a4lwh3qdqwa5t5237");
}
/*
* @Author: LiuYunHu
* @Date: 2024/4/17 9:19
* @Description:
* @Param: []
* @Return: void
**/
@org.junit.jupiter.api.Test
public void createAndRunInstance() throws Exception {
String instanceId = aliYunEcsService.createAndRunInstance();
System.out.println(instanceId);
}