给协议解析使用mq发送用户名密码和ip以及客户端id

dev.car.gateway
冷调 2024-10-09 22:37:17 +08:00
parent 48916dce82
commit 6b571dfddc
25 changed files with 125 additions and 306 deletions

View File

@ -1,8 +1,8 @@
package com.muyu.cargateway.Aliyun; package com.muyu.car.gateway.Aliyun;
import com.aliyun.ecs20140526.Client; import com.aliyun.ecs20140526.Client;
import com.aliyun.teaopenapi.models.Config; import com.aliyun.teaopenapi.models.Config;
import com.muyu.cargateway.config.AliProperties; import com.muyu.car.gateway.config.AliProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;

View File

@ -1,6 +1,6 @@
package com.muyu.cargateway.instance; package com.muyu.car.gateway.Aliyun.instance;
import com.muyu.cargateway.Aliyun.service.AliYunEcsService; import com.muyu.car.gateway.Aliyun.service.AliYunEcsService;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;

View File

@ -1,9 +1,8 @@
package com.muyu.cargateway.instance; package com.muyu.car.gateway.Aliyun.instance;
import com.muyu.cargateway.Aliyun.service.AliYunEcsService; import com.muyu.car.gateway.Aliyun.service.AliYunEcsService;
import com.muyu.cargateway.config.AliProperties; import com.muyu.car.gateway.config.AliProperties;
import com.muyu.cargateway.domain.AliInstance; import com.muyu.car.gateway.domain.AliInstance;
import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationArguments;
@ -28,8 +27,6 @@ public class Sample implements ApplicationRunner{
private AliYunEcsService aliYunEcsService; private AliYunEcsService aliYunEcsService;
@Autowired @Autowired
private AliProperties aliProperties; private AliProperties aliProperties;
@Autowired
private RedisService redisService;
@Override @Override
public void run(ApplicationArguments args) throws Exception { public void run(ApplicationArguments args) throws Exception {
@ -42,17 +39,14 @@ public class Sample implements ApplicationRunner{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
log.info("创建实例成功"); log.info("创建实例成功");
redisService.setCacheList("instanceIds", list); // redisService.setCacheList("instanceIds", list);
try { try {
Thread.sleep(6000); Thread.sleep(9000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
List<AliInstance> aliInstances = aliYunEcsService.selectInstance(list); List<AliInstance> aliInstances = aliYunEcsService.selectInstance(list);
log.info("查询实例信息成功:{}",aliInstances); log.info("================查询实例信息成功:{}",aliInstances);
// 将查询到的实例信息列表存储到Redis中
redisService.setCacheList("instanceList", aliInstances);
log.info("redis存储成功{}", aliInstances);
} }
// @Override // @Override

View File

@ -1,11 +1,11 @@
package com.muyu.cargateway.Aliyun.service; package com.muyu.car.gateway.Aliyun.service;
import com.aliyun.ecs20140526.Client; import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.*; import com.aliyun.ecs20140526.models.*;
import com.aliyun.tea.TeaException; import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions; import com.aliyun.teautil.models.RuntimeOptions;
import com.muyu.cargateway.config.AliProperties; import com.muyu.car.gateway.domain.AliInstance;
import com.muyu.cargateway.domain.AliInstance; import com.muyu.car.gateway.config.AliProperties;
import com.muyu.common.core.exception.ServiceException; import com.muyu.common.core.exception.ServiceException;
import com.muyu.common.redis.service.RedisService; import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@ -49,11 +49,9 @@ public class AliYunEcsService {
* @return id * @return id
*/ */
public List<String> generateInstance(Integer amount) { public List<String> generateInstance(Integer amount) {
redisService.deleteObject("instanceIds"); redisService.deleteObject("oneIpList");
redisService.deleteObject("instanceList"); redisService.deleteObject("oneCount");
redisService.deleteObject("ipList"); redisService.deleteObject("oneVinIp");
redisService.deleteObject("count");
redisService.deleteObject("vinIp");
// 检查生成实例的数量是否有效 // 检查生成实例的数量是否有效
if (amount == null || amount <= 0) { if (amount == null || amount <= 0) {
throw new ServiceException("生成数量不能小于1"); throw new ServiceException("生成数量不能小于1");
@ -140,20 +138,25 @@ public class AliYunEcsService {
for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance bodyInstance : instance) { for (DescribeInstancesResponseBody.DescribeInstancesResponseBodyInstancesInstance bodyInstance : instance) {
// 实例id // 实例id
String instanceId = bodyInstance.getInstanceId(); String instanceId = bodyInstance.getInstanceId();
log.info("实例id为{}", instanceId);
// ip地址 // ip地址
String ipAddress = bodyInstance.getPublicIpAddress().getIpAddress().get(0); String ipAddress = bodyInstance.getPublicIpAddress().getIpAddress().get(0);
log.info("实例ip为{}", ipAddress);
stringArrayList.add(ipAddress);
// 实例状态 // 实例状态
String status = bodyInstance.getStatus(); String status = bodyInstance.getStatus();
log.info("实例状态为:{}", status);
log.info("=======================实例id为{}", instanceId);
log.info("=======================实例ip为{}", ipAddress);
log.info("=======================实例状态为:{}", status);
stringArrayList.add(ipAddress);
AliInstance aliInstance = new AliInstance(instanceId, ipAddress, status); AliInstance aliInstance = new AliInstance(instanceId, ipAddress, status);
aliInstances.add(aliInstance); aliInstances.add(aliInstance);
redisService.setCacheList(instanceId, aliInstances);
aliInstances.remove(aliInstance);
} }
log.info("======================ipList{}", stringArrayList); log.info("======================ipList{}", stringArrayList);
redisService.setCacheList("ipList", stringArrayList); redisService.setCacheList("oneIpList", stringArrayList);
log.info("查询成功"); log.info("查询成功");
} catch (Exception e) { } catch (Exception e) {
log.error("查询服务器实例错误:[{}]", e.getMessage(), e); log.error("查询服务器实例错误:[{}]", e.getMessage(), e);

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway; package com.muyu.car.gateway;
import com.muyu.common.security.annotation.EnableCustomConfig; import com.muyu.common.security.annotation.EnableCustomConfig;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.config; package com.muyu.car.gateway.config;
import lombok.Data; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.config; package com.muyu.car.gateway.config;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger; import org.slf4j.Logger;

View File

@ -1,8 +1,8 @@
package com.muyu.cargateway.controller; package com.muyu.car.gateway.controller;
import com.muyu.cargateway.domain.model.MqttServerModel; import com.muyu.car.gateway.domain.req.VehicleConnectionReq;
import com.muyu.cargateway.domain.req.VehicleConnectionReq; import com.muyu.car.gateway.service.CarOneClickOperationService;
import com.muyu.cargateway.service.CarOneClickOperationService; import com.muyu.car.gateway.domain.model.MqttServerModel;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
/** /**
* *

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableId;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain; package com.muyu.car.gateway.domain;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain.model; package com.muyu.car.gateway.domain.model;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain.properties; package com.muyu.car.gateway.domain.properties;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain.req; package com.muyu.car.gateway.domain.req;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;

View File

@ -1,4 +1,4 @@
package com.muyu.cargateway.domain.resp; package com.muyu.car.gateway.domain.resp;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;

View File

@ -1,6 +1,6 @@
package com.muyu.cargateway.mapper; package com.muyu.car.gateway.mapper;
import com.muyu.cargateway.domain.VehicleConnection; import com.muyu.car.gateway.domain.VehicleConnection;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import java.util.List; import java.util.List;
@ -19,6 +19,8 @@ public interface CarOneClickOperationMapper {
List<String> selectByVehicleVin(String vehicleVin); List<String> selectByVehicleVin(String vehicleVin);
List<String> selectVin();
List<VehicleConnection> getMqttServerModel(String vehicleVin);
} }

View File

@ -1,7 +1,7 @@
package com.muyu.cargateway.service; package com.muyu.car.gateway.service;
import com.muyu.cargateway.domain.model.MqttServerModel; import com.muyu.car.gateway.domain.model.MqttServerModel;
import com.muyu.cargateway.domain.req.VehicleConnectionReq; import com.muyu.car.gateway.domain.req.VehicleConnectionReq;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
/** /**

View File

@ -1,11 +1,12 @@
package com.muyu.cargateway.service.Impl; package com.muyu.car.gateway.service.Impl;
import com.muyu.cargateway.domain.VehicleConnection; import com.muyu.car.gateway.domain.VehicleConnection;
import com.muyu.cargateway.domain.VinIp; import com.muyu.car.gateway.domain.VinIp;
import com.muyu.cargateway.domain.model.MqttServerModel; import com.muyu.car.gateway.domain.model.MqttServerModel;
import com.muyu.cargateway.domain.req.VehicleConnectionReq; import com.muyu.car.gateway.domain.properties.MqttProperties;
import com.muyu.cargateway.mapper.CarOneClickOperationMapper; import com.muyu.car.gateway.domain.req.VehicleConnectionReq;
import com.muyu.cargateway.service.CarOneClickOperationService; import com.muyu.car.gateway.mapper.CarOneClickOperationMapper;
import com.muyu.car.gateway.service.CarOneClickOperationService;
import com.muyu.common.core.domain.Result; import com.muyu.common.core.domain.Result;
import com.muyu.common.redis.service.RedisService; import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@ -15,6 +16,11 @@ import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
import static com.muyu.car.gateway.config.RabbitmqConfig.EXCHANGE_TOPICS_INFORM;
import static com.muyu.car.gateway.config.RabbitmqConfig.ROUTINGKEY_SMS;
/** /**
* @ ToolIntelliJ IDEA * @ ToolIntelliJ IDEA
* @ AuthorCHX * @ AuthorCHX
@ -45,10 +51,9 @@ public class CarOneClickOperationServiceImpl implements CarOneClickOperationServ
public Result<MqttServerModel> getConnect(VehicleConnectionReq vehicleConnectionReq) { public Result<MqttServerModel> getConnect(VehicleConnectionReq vehicleConnectionReq) {
log.info("车辆连接请求:{}",vehicleConnectionReq.toString()); log.info("车辆连接请求:{}",vehicleConnectionReq.toString());
// 使用交换机发送消息 // // 使用交换机发送消息 给事件系统发
rabbitTemplate.convertAndSend("exchange_topics_inform","inform.#.email.#",vehicleConnectionReq.getVehicleVin()); // rabbitTemplate.convertAndSend("exchange_topics_inform","inform.#.email.#",vehicleConnectionReq.getVehicleVin());
log.info("发送消息成功:{}",vehicleConnectionReq.getVehicleVin()); // log.info("发送消息成功:{}",vehicleConnectionReq.getVehicleVin());
VehicleConnection vehicleConnection = new VehicleConnection(); VehicleConnection vehicleConnection = new VehicleConnection();
//车辆vin //车辆vin
@ -57,44 +62,67 @@ public class CarOneClickOperationServiceImpl implements CarOneClickOperationServ
vehicleConnection.setUsername(vehicleConnectionReq.getUsername()); vehicleConnection.setUsername(vehicleConnectionReq.getUsername());
//密码(vin+时间戳+随机数) //密码(vin+时间戳+随机数)
vehicleConnection.setPassword(vehicleConnectionReq.getVehicleVin()+vehicleConnectionReq.getTimestamp()+vehicleConnectionReq.getNonce()); vehicleConnection.setPassword(vehicleConnectionReq.getVehicleVin()+vehicleConnectionReq.getTimestamp()+vehicleConnectionReq.getNonce());
//添加连接信息 //查询有没有这辆车的vin码
carOneClickOperationMapper.addConnect(vehicleConnection); List<String> selectVehicle = carOneClickOperationMapper.selectByVehicleVin(vehicleConnectionReq.getVehicleVin());
if(selectVehicle.isEmpty()){
//添加连接信息
carOneClickOperationMapper.addConnect(vehicleConnection);
log.info("车辆上线成功");
}else {
throw new RuntimeException("车辆无法重复上线");
}
//先判断vin码 //先判断vin码
HashOperations<String, String, String> hashOps = redisTemplate.opsForHash(); HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
String vinIp = hashOps.get("vinIp", vehicleConnectionReq.getVehicleVin()); String vinIp = hashOps.get("oneVinIp", vehicleConnectionReq.getVehicleVin());
if(vinIp!=null){ if(vinIp!=null){
log.info("车辆绑定ip失败已经存在");
throw new RuntimeException("车辆绑定ip失败已经存在"); throw new RuntimeException("车辆绑定ip失败已经存在");
} }
MqttProperties mqttProperties = new MqttProperties();
List<VehicleConnection> vehicleVin = selectByVehicleVin(vehicleConnectionReq.getVehicleVin());
for (VehicleConnection connection : vehicleVin) {
mqttProperties.setClientId(connection.getVehicleVin());
mqttProperties.setUserName(connection.getUsername());
mqttProperties.setPassword(connection.getPassword());
}
mqttProperties.setTopic("vehicle");
mqttProperties.setQos(0);
//判断redis有没有count键 //判断redis有没有count键
if(redisTemplate.hasKey("count")){ if(redisTemplate.hasKey("oneCount")){
//取出count //取出count
Integer count = Integer.valueOf(redisTemplate.opsForValue().get("count")); Integer count = Integer.valueOf(redisTemplate.opsForValue().get("oneCount"));
if(count == 1){ if(count == 1){
redisTemplate.opsForValue().set("count",String.valueOf(0)); redisTemplate.opsForValue().set("oneCount",String.valueOf(0));
}else { }else {
redisTemplate.opsForValue().set("count",String.valueOf(count+1)); redisTemplate.opsForValue().set("oneCount",String.valueOf(count+1));
} }
//根据游标count获取服务IP //根据游标count获取服务IP
// String ip = redisTemplate.opsForList().index("ipList", count); // String ip = redisTemplate.opsForList().index("ipList", count);
Object ipList = redisService.redisTemplate.opsForList().index("ipList", count); Object ipList = redisService.redisTemplate.opsForList().index("oneIpList", count);
log.info("=========================ipList:"+ipList); log.info("=========================oneIpList:"+ipList);
//关联车辆和服务 //关联车辆和服务
this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ipList.toString())); this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ipList.toString()));
//响应信息 //响应信息
log.info("车辆:{}",vehicleConnectionReq.getVehicleVin()+"绑定成功:{}",ipList); log.info("车辆:{}",vehicleConnectionReq.getVehicleVin()+"绑定成功:{}",ipList);
mqttProperties.setBroker("tcp://"+ipList+":1883");
// 使用交换机发送消息
rabbitTemplate.convertAndSend(EXCHANGE_TOPICS_INFORM,ROUTINGKEY_SMS,mqttProperties);
log.info("============================发送消息成功:{}",mqttProperties);
return Result.success(new MqttServerModel("tcp://"+ipList+":1883","vehicle")); return Result.success(new MqttServerModel("tcp://"+ipList+":1883","vehicle"));
}else { }else {
redisTemplate.opsForValue().set("count",String.valueOf(0)); redisTemplate.opsForValue().set("oneCount",String.valueOf(0));
//根据游标count获取服务器Ip //根据游标count获取服务器Ip
Object ipList = redisService.redisTemplate.opsForList().index("ipList", 0); Object ipList = redisService.redisTemplate.opsForList().index("oneIpList", 0);
//关联车辆和服务 //关联车辆和服务
this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ipList.toString())); this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ipList.toString()));
//响应信息 //响应信息
log.info("车辆:{}",vehicleConnectionReq.getVehicleVin(),"与:{}绑定成功",ipList); log.info("车辆:{}",vehicleConnectionReq.getVehicleVin(),"与:{}绑定成功",ipList);
mqttProperties.setBroker("tcp://"+ipList+":1883");
// 使用交换机发送消息
rabbitTemplate.convertAndSend(EXCHANGE_TOPICS_INFORM,ROUTINGKEY_SMS,mqttProperties);
log.info("============================发送消息成功:{}",mqttProperties);
return Result.success(new MqttServerModel("tcp://"+ipList+":1883","vehicle")); return Result.success(new MqttServerModel("tcp://"+ipList+":1883","vehicle"));
} }
} }
@ -105,6 +133,15 @@ public class CarOneClickOperationServiceImpl implements CarOneClickOperationServ
if (vinIp == null || vinIp.getVin() == null || vinIp.getVin().isEmpty() || vinIp.getIp() == null || vinIp.getIp().isEmpty()) { if (vinIp == null || vinIp.getVin() == null || vinIp.getVin().isEmpty() || vinIp.getIp() == null || vinIp.getIp().isEmpty()) {
throw new IllegalArgumentException("vin 或 ip 不能为空或无效"); throw new IllegalArgumentException("vin 或 ip 不能为空或无效");
} }
redisTemplate.opsForHash().put("vinIp", vinIp.getVin(), vinIp.getIp()); redisTemplate.opsForHash().put("oneVinIp", vinIp.getVin(), vinIp.getIp());
}
/**
*
* @param vehicleVin vin
* @return
*/
public List<VehicleConnection> selectByVehicleVin(String vehicleVin) {
return carOneClickOperationMapper.getMqttServerModel(vehicleVin);
} }
} }

View File

@ -1,87 +0,0 @@
package com.muyu.cargateway.domain.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ ToolIntelliJ IDEA
* @ AuthorCHX
* @ Date2024-09-26-20:23
* @ Version1.0
* @ Description
* @author Lenovo
*/
@Data
@Log4j2
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TaskModel {
/**
* false
* truefalse
*/
private final AtomicBoolean status =new AtomicBoolean(Boolean.FALSE);
/**
*
*/
private CountDownLatch countDownLatch;
/**
*
*/
private LinkedBlockingDeque<String> carQueue =new LinkedBlockingDeque<>();
/**
*
* true
* false
* @return
*/
private boolean isExecution(){
return !status.get();
}
/**
*
*/
private String taskName;
/**
*
*/
private Integer taskExecutionCount=0;
/**
*
*/
private Long taskStartTime;
/**
*
*/
private AtomicInteger taskSuccessSum=new AtomicInteger();
/**
*
*/
private AtomicInteger taskErrorSum=new AtomicInteger();
/**
*
* @return true
*/
public boolean hashNext(){
return !carQueue.isEmpty();
}
/**
*
* @return VIN
*/
public String next(){
return carQueue.poll();
}
}

View File

@ -1,135 +0,0 @@
package com.muyu.cargateway.utils;
import com.aliyun.ecs20140526.Client;
import com.aliyun.ecs20140526.models.DeleteInstanceRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesRequest;
import com.aliyun.ecs20140526.models.DescribeInstancesResponse;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.log4j.Log4j2;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @ ToolIntelliJ IDEA
* @ AuthorCHX
* @ Date2024-10-02-16:04
* @ Version1.0
* @ Descriptionecs
* @author Lenovo
*/
@Log4j2
public class ECSTool {
public static final String ACCESS_KEY_ID = "LTAI5tDH3FyRx4PRr6anx2TL";
public static final String ACCESS_KEY_SECRET = "xdQnX2tDattY50raNkUWmHzE2tondP";
public static Client createClient() throws Exception {
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
Config config = new Config()
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
.setAccessKeyId(ACCESS_KEY_ID)
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
.setAccessKeySecret(ACCESS_KEY_SECRET);
// Endpoint 请参考 https://api.aliyun.com/product/Ecs
config.endpoint = "ecs-cn-hangzhou.aliyuncs.com";
return new Client(config);
}
public static void runEcsInstance(String regionId, String launchTemplateId) throws Exception {
Client client = ECSTool.createClient();
RunInstancesRequest request = new RunInstancesRequest();
request.setRegionId(regionId)
.setLaunchTemplateId(launchTemplateId);
RuntimeOptions runtimeOptions = new RuntimeOptions();
try{
client.runInstancesWithOptions(request, runtimeOptions);
}catch (Exception error){
// 处理API调用过程中出现的异常
System.out.println(error.getMessage());
if (error instanceof TeaException) {
// 处理特定类型的异常如TeaException
TeaException teaError = (TeaException) error;
// 打印诊断推荐链接
System.out.println(teaError.getData().get("Recommend"));
// 断言错误信息
com.aliyun.teautil.Common.assertAsString(teaError.getMessage());
} else {
// 处理其他类型的异常
System.out.println(error.getMessage());
}
}
}
/**
*
*/
public static void runEcsRemove(String instanceId) throws Exception {
Client client = ECSTool.createClient();
DeleteInstanceRequest deleteInstancesRequest = new DeleteInstanceRequest();
deleteInstancesRequest.setInstanceId(instanceId);
RuntimeOptions runtimeOptions = new RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
client.deleteInstanceWithOptions(deleteInstancesRequest, runtimeOptions);
} 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);
}
}
/**
*
* @param regionId ID
*/
public static List<String> findInstance(String regionId) throws Exception {
Client client = ECSTool.createClient();
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
describeInstancesRequest.setRegionId(regionId);
RuntimeOptions runtimeOptions = new RuntimeOptions();
List<String> stringArrayList = new ArrayList<>();
try {
DescribeInstancesResponse response = client.describeInstancesWithOptions(describeInstancesRequest, runtimeOptions);
List<List<String>> ipListList = response.getBody().instances.getInstance().stream().map(instance -> instance.publicIpAddress.ipAddress).collect(Collectors.toList());
for (List<String> strings : ipListList) {
for (String ip : strings) {
stringArrayList.add(ip);
}
return stringArrayList;
}
} catch (TeaException error) {
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
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"));
Common.assertAsString(error.message);
}
return null;
}
}

View File

@ -2,7 +2,7 @@
<!DOCTYPE mapper <!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.muyu.cargateway.mapper.CarOneClickOperationMapper"> <mapper namespace="com.muyu.car.gateway.mapper.CarOneClickOperationMapper">
<insert id="addConnect"> <insert id="addConnect">
@ -14,8 +14,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectByVehicleVin" resultType="java.lang.String"> <select id="selectByVehicleVin" resultType="java.lang.String">
select vehicle_vin from car_one_click_operation where vehicle_vin = #{vehicleVin} select vehicle_vin from car_one_click_operation where vehicle_vin = #{vehicleVin}
</select> </select>
<select id="selectVin" resultType="java.lang.String"> <select id="getMqttServerModel" resultType="com.muyu.car.gateway.domain.VehicleConnection">
select vehicle_vin from car_one_click_operation where vehicle_vin=#{vehicleVin} select
vehicle_vin,user_name,password
from
car_one_click_operation
where
vehicle_vin = #{vehicleVin}
</select> </select>