feat commit

网关负载功能
master
玉安君 2024-04-18 21:38:49 +08:00
parent 4d1cb943ac
commit 3857e3a875
24 changed files with 658 additions and 186 deletions

View File

@ -156,13 +156,13 @@ public class RedisService {
/**
* Set
*
* @param key
* @param key
* @param setValue
* @return
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final T setValue) {
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
setOperation.add(setValue);
setOperation.add(setValue);
return setOperation;
}
@ -272,8 +272,6 @@ public class RedisService {
}
/**
* Zset
*
@ -310,6 +308,7 @@ public class RedisService {
/**
*
*
* @param zkey
* @param start
* @param end
@ -329,46 +328,50 @@ public class RedisService {
/**
* ,delta,
*
* @param zkey
* @param value
* @param delta
* @param <T>
*/
public <T> Double incrementScore(final String zkey, final T value, final Double delta){
return redisTemplate.opsForZSet().incrementScore(zkey,value,delta);
public <T> Double incrementScore(final String zkey, final T value, final Double delta) {
return redisTemplate.opsForZSet().incrementScore(zkey, value, delta);
}
/**
*
*
* @param zkey
* @param values
* @return
* @param <T>
* @return
*/
public <T> Long removeCacheZsetBatch(final String zkey,final T... values){
return redisTemplate.opsForZSet().remove(zkey,values);
public <T> Long removeCacheZsetBatch(final String zkey, final T... values) {
return redisTemplate.opsForZSet().remove(zkey, values);
}
/**
* ,
*
* @param zkey
* @param start
* @param end
* @return
*/
public Set<Double> reverseRange(final String zkey,final Long start,final Long end){
return redisTemplate.opsForZSet().reverseRange(zkey,start,end);
public Set<Double> reverseRange(final String zkey, final Long start, final Long end) {
return redisTemplate.opsForZSet().reverseRange(zkey, start, end);
}
/**
*
*
* @param zkey
* @param min
* @param max
* @return
*/
public Set<Double> rangeByScore(final String zkey,final Double min,final Double max){
return redisTemplate.opsForZSet().rangeByScore(zkey,min,max);
public Set<Double> rangeByScore(final String zkey, final Double min, final Double max) {
return redisTemplate.opsForZSet().rangeByScore(zkey, min, max);
}
/**
@ -377,7 +380,7 @@ public class RedisService {
* @param zkey
* @return
*/
public ZSetOperations.TypedTuple getCacheZsetMin(final String zkey){
public ZSetOperations.TypedTuple getCacheZsetMin(final String zkey) {
ZSetOperations.TypedTuple typedTuple = redisTemplate.opsForZSet().popMin(zkey);
return typedTuple;
}
@ -393,13 +396,37 @@ public class RedisService {
return redisTemplate.keys(pattern);
}
public void deleteCacheSet(String key) {
public void deleteCacheSet(final String key) {
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.remove(key);
}
public <T> void deleteCacheSetValue(String key, T value) {
public <T> void deleteCacheSetValue(final String key, final T value) {
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.remove(key,value);
setOperations.remove(key, value);
}
/**
* @description: Listvalue
* @author: LiYuan
* @param: key index
* @return: value
**/
public <T> T getcacheListValue(final String key, final Long index) {
ListOperations listOperations = redisTemplate.opsForList();
return (T) listOperations.index(key, index);
}
/**
* @description: String
* @author: LiYuan
* @param: key,number
* @return: Long
**/
public Long increment(final String key,final Long number) {
ValueOperations valueOperations = redisTemplate.opsForValue();
return valueOperations.increment(key,number);
}
}

View File

@ -0,0 +1,45 @@
package com.zhilian.online.Timer;
import com.zhilian.online.uitls.AliyunOpenAPIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.Timer
* @Author: LiYuan
* @CreateTime: 2024-04-17 21:53
* @Description:
* @Version: 1.0
*/
@Component
@Slf4j
public class LoadObserver {
/**
* api
*/
@Autowired
private AliyunOpenAPIUtils aliyunOpenAPIUtils;
/**
*
*/
@Scheduled(cron = "0/10 * * * * ?")
public void addInstance(){
}
/**
*
*/
@Scheduled(cron = "0/10 * * * * ?")
public void ReduceInstance(){
}
}

View File

@ -4,6 +4,7 @@ import com.zhilian.common.security.annotation.EnableCustomConfig;
import com.zhilian.common.security.annotation.EnableMyFeignClients;
import com.zhilian.common.swagger.annotation.EnableCustomSwagger2;
import com.zhilian.online.controller.OnlineLoadCenterController;
import com.zhilian.online.domain.req.EcsCreateReq;
import com.zhilian.online.uitls.AliyunOpenAPIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -11,6 +12,7 @@ import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.aliyun.ecs20140526.models.RunInstancesRequest;
/**
* @version:
@ -23,16 +25,41 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@EnableMyFeignClients
@SpringBootApplication
@Slf4j
public class ZhiLianOnlineApplication implements ApplicationRunner{
public class ZhiLianOnlineApplication implements ApplicationRunner {
@Autowired
private AliyunOpenAPIUtils aliyunOpenAPIUtils;
public static void main(String[] args) {
SpringApplication.run(ZhiLianOnlineApplication.class,args);
SpringApplication.run(ZhiLianOnlineApplication.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("项目启动,调用创建实例方法");
// aliyunOpenAPIUtils.createInstance();
RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk();
systemDisk = systemDisk.setSize("20").setCategory("cloud_efficiency");
EcsCreateReq ecs = EcsCreateReq.builder()
.regionId("cn-zhangjiakou")
.imageId("m-8vbfx0e48cekro0f13bx")
.instanceType("ecs.t6-c1m1.large")
.securityGroupId("sg-8vb49jd1c1lsa3akwo02")
.vSwitchId("vsw-8vb0krtyfdmb27nhcmzc2")
.instanceName("gather-node")
.internetMaxBandwidthIn(80)
.internetMaxBandwidthOut(10)
.uniqueSuffix(true)
.password("142730.Ly")
.zoneId("cn-zhangjiakou-c")
.internetChargeType("PayByTraffic")
.systemDiskSize("20")
.systemDickCategory("cloud_efficiency")
.amount(1)
.minAmount(1)
.periodUnit("Week")
.period(1)
.instanceChargeType("PostPaid")
.privateIpAddress("10.10.27.1")
.build();
aliyunOpenAPIUtils.createInstance(ecs);
}
}

View File

@ -16,7 +16,7 @@ public class OnlineConstants {
/**
*
*/
public static final String ONLINE_TOKEN_PREFIX = "online_token:";
public static final String NODE_TOKEN_PREFIX = "node_token:";
/**
*
@ -26,11 +26,26 @@ public class OnlineConstants {
/**
*
*/
public static final String GATHER_LOAD_CONTROL = "gather_info_control";
public static final String GATHER_LOAD_PREFIX = "gather:load:";
/**
*
* 线
*/
public static final String ONLINE_VEHICLE = "online_vehicle:";
public static final String ONLINE_GATHER_PREFIX = "online_vehicle:";
/**
* http
*/
public static final String HTTP_PREFIX = "http://";
/**
* https
*/
public static final String HTTPS_PREFIX = "https://";
/**
* fluxMQ
*/
public static final String FLUXMQ_INFO_URL = ":8080/public/cluster";

View File

@ -1,12 +1,9 @@
package com.zhilian.online.consumer;
import com.alibaba.fastjson.JSON;
import com.zhilian.common.core.constant.Constants;
import com.zhilian.common.redis.service.RedisService;
import com.zhilian.online.config.RabbitConfig;
import com.zhilian.online.constans.OnlineConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@ -54,8 +51,8 @@ public class DeadQueueConsumer {
if (Constants.FAIL == responseCode){
log.error("节点{}上线失败",gatherMsg);
//上线失败需要将该节点的负载均衡缓存删除
if (redisService.hasKey(OnlineConstants.ONLINE_TOKEN_PREFIX + "")){
redisService.removeCacheZsetBatch(OnlineConstants.ONLINE_TOKEN_PREFIX + "");
if (redisService.hasKey(OnlineConstants.NODE_TOKEN_PREFIX + "")){
redisService.removeCacheZsetBatch(OnlineConstants.NODE_TOKEN_PREFIX + "");
}
}
} catch (Exception e) {

View File

@ -1,32 +0,0 @@
package com.zhilian.online.controller;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.service.OnlineGatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 20:46
*/
@RestController
@RequestMapping("/gather")
public class OnlineGatherController {
/**
*
*/
@Autowired
private OnlineGatherService onlineGatherService;
}

View File

@ -40,14 +40,14 @@ public class OnlineLoadCenterController extends BaseController {
/**
* @description: , 访
* @author: LiY
* @author: LiYuan
* @param: vehicle
* @return: Result<OnlineAccount>
**/
@GetMapping("/applyForReg")
public Result<String> applyForReg() {
log.info("申请注册令牌");
return onlineLoadCenterService.applyForReg();
public Result<String> applyForReg(String clusterId) {
log.info("节点{}申请注册令牌",clusterId);
return onlineLoadCenterService.applyForReg(clusterId);
}

View File

@ -1,49 +0,0 @@
package com.zhilian.online.controller;/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/30 11:18
*/
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.domain.model.MqttServerModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.controller
* @Author: LiYuan
* @CreateTime: 2024-03-30 11:18
* @Description: 线
* @Version: 1.0
*/
@RestController
@RequestMapping("/verify")
public class OnlineVerifyController {
/**
* mqtt
*/
@Value("${mqtt.server.broker}")
private String broker;
/**
*
*/
@Value("${mqtt.server.topic}")
private String topic;
@PostMapping("/vehicleConnection")
public Result<MqttServerModel> vehicleConnection() {
return Result.success(
MqttServerModel.builder()
.broker(broker)
.topic(topic)
.build()
);
}
}

View File

@ -0,0 +1,35 @@
package com.zhilian.online.domain.model;
import lombok.*;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.domain.model
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:47
* @Description:
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class GatewayNodeInfo {
/**
* id
*/
private String nodeId;
/**
* IP
*/
private String publicIpAddress;
/**
* IP
*/
private String privateIpAddress;
}

View File

@ -36,12 +36,12 @@ public class EcsCreateReq {
/**
* ID
*/
private String ImageId;
private String imageId;
/**
*
*/
private String InstanceType;
private String instanceType;
/**
* ID
@ -85,37 +85,37 @@ public class EcsCreateReq {
private String zoneId;
/**
*
*
*/
private String internetChargeType;
/**
*
*
*/
private Integer amount;
/**
*
*
*/
private Integer minAmount;
/**
*
*
*/
private String periodUnit;
/**
*
*
*/
private Integer period;
/**
*
*
*/
private String instanceChargeType;
/**
*
* IP
*/
private String privateIpAddress;

View File

@ -9,7 +9,7 @@ import javax.validation.constraints.NotBlank;
* @BelongsPackage: com.zhilian.online.domain.req
* @Author: LiYuan
* @CreateTime: 2024-04-12 15:37
* @Description: openAPI
* @Description: openAPI
* @Version: 1.0
*/
@Data

View File

@ -0,0 +1,26 @@
package com.zhilian.online.load.abs;
import com.zhilian.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.abs
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:09
* @Description:
* @Version: 1.0
*/
public abstract class GatewayCacheAbs<K> {
@Autowired
public RedisService redisService;
public abstract String getPre();
public String encode(K key) {
return getPre() + key;
}
}

View File

@ -0,0 +1,66 @@
package com.zhilian.online.load.cache;
import com.zhilian.common.redis.service.RedisService;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:11
* @Description:
* @Version: 1.0
*/
@Component
public class GatewayLoadNodeCache extends GatewayCacheAbs<String> {
private final static String gatewayLoadNodeKey = "node";
@Override
public String getPre() {
return "gateway:load:";
}
/**
* @description:
* @author: LiYuan
* @param: nodeList
* @return: void
**/
public void put(List<String> nodeList) {
redisService.deleteObject(encode(gatewayLoadNodeKey));
redisService.setCacheList(encode(gatewayLoadNodeKey), nodeList);
}
/**
* @description:
* @author: LiYuan
* @param: null
* @return: List<String>
**/
public List<String> get() {
return redisService.getCacheList(encode(gatewayLoadNodeKey));
}
/**
* @description:
* @author: LiYuan
* @param: index
* @return: String node
**/
public String getByIndex(Long index){
if (null == index || index > 100){
throw new RuntimeException("下标违法,不在[0-100]内");
}
return redisService.getcacheListValue(encode(gatewayLoadNodeKey),index);
}
}

View File

@ -0,0 +1,71 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:34
* @Description:
* @Version: 1.0
*/
@Component
public class GatewayLoadSeriesCache extends GatewayCacheAbs<String> {
private final static String gatewayLoadSeriesKey = "series";
@Override
public String getPre() {
return "gateway:load:";
}
/**
* @description: Bean
* @author: LiYuan
* @param:
* @return:
**/
@PostConstruct
public void init() {
redisService.setCacheObject(encode(gatewayLoadSeriesKey), 0);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return: Long
**/
public Long incrementAndGet() {
return redisService.increment(encode(gatewayLoadSeriesKey), 1L);
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public Long get() {
return redisService.getCacheObject(encode(gatewayLoadSeriesKey));
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void reset() {
this.init();
}
}

View File

@ -0,0 +1,68 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.domain.model.GatewayNodeInfo;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:44
* @Description: String key + nodeInfo
* @Version: 1.0
*/
@Component
public class GatewayNodeCache extends GatewayCacheAbs<String > {
@Override
public String getPre() {
return "gateway:node:info";
}
/**
* @description:
* @author: LiYuan
* @param: GatewayNodeInfo
* @return:
**/
public void put(GatewayNodeInfo gatewayNodeInfo){
redisService.setCacheObject(encode(gatewayNodeInfo.getNodeId()),gatewayNodeInfo);
}
/**
* @description:
* @author: LiYuan
* @param: nodeId Id
* @return:
**/
public GatewayNodeInfo get(String nodeId){
return redisService.getCacheObject(encode(nodeId));
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public List<GatewayNodeInfo> get(){
return redisService.getCacheObject(encode(getPre()));
}
/**
* @description:
* @author: LiYuan
* @param:
* @return:
**/
public void remove(String nodeId){
redisService.deleteObject(encode(nodeId));
}
}

View File

@ -0,0 +1,41 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 20:03
* @Description: Zset
* @Version: 1.0
*/
@Component
public class GatewayNodeLoadInfoCache extends GatewayCacheAbs<String > {
private final static String gatewayZset = "node-connects:";
@Override
public String getPre() {
return "gateway:Zset:";
}
/**
* @description: Zset
* @author: LiYuan
* @param:
* @return:
**/
public Map<Object,Double> get(){
return redisService.getCacheObject(encode(gatewayZset));
}
}

View File

@ -0,0 +1,56 @@
package com.zhilian.online.load.cache;
import com.zhilian.online.load.abs.GatewayCacheAbs;
import org.springframework.stereotype.Component;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.load.cache
* @Author: LiYuan
* @CreateTime: 2024-04-18 19:58
* @Description: 线
* @Version: 1.0
*/
@Component
public class GatewayVehicleNodeCaChe extends GatewayCacheAbs<String> {
private final static String gatewayCarBusinessKey = "business:";
@Override
public String getPre() {
return "gateway:car:";
}
/**
* @description:
* @author: LiYuan
* @param: String vin, String nodeId
* @return:
**/
public void put(String vin, String nodeId) {
redisService.setCacheObject(encode(gatewayCarBusinessKey) + vin,nodeId);
}
/**
* @description:
* @author: LiYuan
* @param: String vin
* @return:
**/
public void remove(String vin){
redisService.deleteObject(encode(gatewayCarBusinessKey) + vin);
}
/**
* @description:
* @author: LiYuan
* @param: String vin
* @return:
**/
public String get(String vin){
return redisService.getCacheObject(encode(gatewayCarBusinessKey) + vin);
}
}

View File

@ -1,17 +0,0 @@
package com.zhilian.online.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 20:48
*/
@Mapper
public interface OnlineGatherMapper{
}

View File

@ -17,7 +17,7 @@ public interface OnlineLoadCenterService{
* @param: vehicle
* @return: Result<OnlineAccount>
**/
Result<String> applyForReg();
Result<String> applyForReg(String clusterId);
/**
* @description: 使

View File

@ -1,22 +0,0 @@
package com.zhilian.online.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.mapper.OnlineGatherMapper;
import com.zhilian.online.service.OnlineGatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @version:
* @Author: LiYuan
* @description:
* @date: 2024/3/29 20:48
*/
@Service
public class OnlineGatherServiceImpl implements OnlineGatherService {
@Autowired
private OnlineGatherMapper onlineGatherMapper;
}

View File

@ -9,6 +9,7 @@ import com.zhilian.online.constans.OnlineConstants;
import com.zhilian.online.domain.ApifoxModel;
import com.zhilian.online.mapper.OnlineLoadCenterMapper;
import com.zhilian.online.service.OnlineLoadCenterService;
import com.zhilian.online.uitls.MqttUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
@ -47,6 +48,12 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService{
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* MQTT
*/
@Autowired
private MqttUtil mqttUtil;
/**
* @description: , 访
* @author: LiYuan
@ -54,13 +61,13 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService{
* @return: Result<OnlineAccount>
**/
@Override
public Result<String> applyForReg() {
public Result<String> applyForReg(String clusterId) {
//生成一次性令牌
String token = IdUtils.fastSimpleUUID();
//将令牌信息缓存到Redis中
redisService.setCacheObject(OnlineConstants.ONLINE_TOKEN_PREFIX + token,token, OnlineConstants.ONLINE_TOKEN_EXPIRE, TimeUnit.SECONDS);
redisService.setCacheObject(OnlineConstants.NODE_TOKEN_PREFIX + clusterId,token, OnlineConstants.ONLINE_TOKEN_EXPIRE, TimeUnit.SECONDS);
//将令牌信息返回客户端
return Result.success(token);
@ -76,16 +83,17 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService{
@Override
public Result regGather(ApifoxModel apifoxModel) {
//判断登录令牌是否过期,一致
if (!redisService.hasKey(OnlineConstants.ONLINE_TOKEN_PREFIX + apifoxModel.getToken())) {
if (!redisService.hasKey(OnlineConstants.NODE_TOKEN_PREFIX + apifoxModel.getClusterId())) {
return Result.error("令牌已过期");
}
String token = redisService.getCacheObject(OnlineConstants.ONLINE_TOKEN_PREFIX + apifoxModel.getToken());
String token = redisService.getCacheObject(OnlineConstants.NODE_TOKEN_PREFIX + apifoxModel.getClusterId());
if (!token.equals(apifoxModel.getToken())){
return Result.error("令牌错误");
}
//为该节点创建负载均衡缓存
redisService.setCacheZsetValue(OnlineConstants.GATHER_LOAD_CONTROL + apifoxModel.getClusterId(), JSON.toJSONString(apifoxModel), 0.0);
//为该节点创建Zset负载均衡缓存,将该节点加入List在线节点缓存
redisService.setCacheZsetValue(OnlineConstants.GATHER_LOAD_PREFIX, apifoxModel.getClusterId(), 0.0);
//向RabbitMQ||RocketMQ发送30s延迟消息,确保后续节点上线
rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_NAME, RabbitConfig.DELAY_ROUTING_KEY, JSON.toJSONString(apifoxModel));
@ -110,10 +118,10 @@ public class OnlineLoadCenterServiceImpl implements OnlineLoadCenterService{
throw new RuntimeException("车辆未登记");
}
//获取负载最少的车辆进行链接
ZSetOperations.TypedTuple cacheZsetMin = redisService.getCacheZsetMin(OnlineConstants.GATHER_LOAD_CONTROL);
ZSetOperations.TypedTuple cacheZsetMin = redisService.getCacheZsetMin(OnlineConstants.GATHER_LOAD_PREFIX);
//存放节点车辆信息
redisService.setCacheObject(OnlineConstants.ONLINE_VEHICLE+vin,1);
redisService.setCacheObject(OnlineConstants.GATHER_LOAD_PREFIX+vin,1);
//发送延迟队列确定车辆上线
rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE_FOR_CAR, RabbitConfig.DELAY_ROUTING_FOR_CAR,vin);

View File

@ -3,12 +3,14 @@ package com.zhilian.online.uitls;
import com.aliyun.ecs20140526.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.zhilian.common.core.domain.Result;
import com.zhilian.online.domain.EcsInstance;
import com.zhilian.online.domain.req.EcsCreateReq;
import com.zhilian.online.domain.req.EcsQueryReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import com.aliyun.ecs20140526.Client;
@ -35,6 +37,9 @@ public class AliyunOpenAPIUtils {
@Qualifier(value = "AliyunClient")
private Client aliyunClient;
@Value("aliyun.ecs.region-id")
private String regionId;
/**
*
@ -76,20 +81,25 @@ public class AliyunOpenAPIUtils {
* @param:
* @return: void
**/
public void createInstance(EcsCreateReq ecsCreateReq) {
public List<String> createInstance(EcsCreateReq ecsCreateReq) {
//创建实例请求
RunInstancesRequest runInstancesRequest = makeRunInstancesRequest(ecsCreateReq);
RuntimeOptions runtime = new RuntimeOptions();
List<String> instanceIds = new ArrayList<>();
try {
// 复制代码运行请自行打印 API 的返回值
RunInstancesResponse res = aliyunClient.runInstancesWithOptions(runInstancesRequest, runtime);
//打印执行结果
RunInstancesResponseBody body = res.getBody();
instanceIds = body.getInstanceIdSets().getInstanceIdSet();
log.info("执行结果:[{}],请求ID:[{}],创建实例ID:[{}]",
200 == res.getStatusCode() ? "创建成功" : "创建失败",
body.getRequestId(), body.getInstanceIdSets().getInstanceIdSet());
body.getRequestId(), instanceIds);
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]",
error.getCode(), error.getMessage(), error.getData());
@ -98,6 +108,38 @@ public class AliyunOpenAPIUtils {
log.error("code:[{}],message:[{}],data:[{}]",
error.getCode(), error.getMessage(), error.getData());
}
return instanceIds;
}
public Result deleteInstance(String instanceId) {
Result result = new Result<>();
DeleteInstancesRequest deleteInstancesRequest = new DeleteInstancesRequest()
.setRegionId(regionId)
.setDryRun(false)
.setForce(true)
.setTerminateSubscription(false)
.setInstanceId(java.util.Arrays.asList(
instanceId
));
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
DeleteInstancesResponse deleteInstancesResponse = aliyunClient.deleteInstancesWithOptions(deleteInstancesRequest, runtime);
Integer statusCode = deleteInstancesResponse.getStatusCode();
DeleteInstancesResponseBody body = deleteInstancesResponse.getBody();
log.info(200 == statusCode ? "删除成功" : "删除失败");
result.setCode(statusCode);
result.setData(body);
result.setMsg(200 == statusCode ? "删除成功" : "删除失败");
} catch (TeaException error) {
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
log.error("code:[{}],message:[{}],data:[{}]", error.getCode(), error.getMessage(), error.getData());
}
return result;
}
@ -109,7 +151,7 @@ public class AliyunOpenAPIUtils {
**/
public DescribeInstancesRequest setQueryReq(EcsQueryReq ecsQueryReq) {
return new DescribeInstancesRequest()
.setRegionId(ecsQueryReq.getRegionId())
.setRegionId(regionId)
.setInstanceName(ecsQueryReq.getInstanceName())
.setPageNumber(ecsQueryReq.getPageNumber())
.setPageSize(ecsQueryReq.getPageSize())
@ -141,7 +183,7 @@ public class AliyunOpenAPIUtils {
EcsInstance ecsInstance = EcsInstance.builder()
.instanceId(item.getInstanceId())
.instanceName(item.getInstanceName())
.regionId(item.getRegionId())
.regionId(regionId)
.status(item.getStatus())
.instanceType(item.getInstanceType())
.cpu(item.getCpu())
@ -165,14 +207,21 @@ public class AliyunOpenAPIUtils {
return ecsInstances;
}
public RunInstancesRequest makeRunInstancesRequest(EcsCreateReq ecsCreateReq){
/**
*
*
* @param: ecsCreateReq
* @return: RunInstancesRequest
*/
public RunInstancesRequest makeRunInstancesRequest(EcsCreateReq ecsCreateReq) {
//构建磁盘配置
RunInstancesRequest.RunInstancesRequestSystemDisk systemDisk = new RunInstancesRequest.RunInstancesRequestSystemDisk()
.setSize(ecsCreateReq.getSystemDiskSize())
.setCategory(ecsCreateReq.getSystemDickCategory());
//构建创建实例请求
RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
.setRegionId(ecsCreateReq.getRegionId())
.setRegionId(regionId)
.setImageId(ecsCreateReq.getImageId())
.setInstanceType(ecsCreateReq.getInstanceType())
.setSecurityGroupId(ecsCreateReq.getSecurityGroupId())

View File

@ -0,0 +1,68 @@
package com.zhilian.online.uitls;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhilian.online.constans.OnlineConstants;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.RequestBuilder;
import java.io.IOException;
/**
* @BelongsProject: smart-cloud-server
* @BelongsPackage: com.zhilian.online.uitls
* @Author: LiYuan
* @CreateTime: 2024-04-17 21:41
* @Description: mqtt
* @Version: 1.0
*/
@Component
@Slf4j
public class MqttUtil {
/**
* @description: ipmqttfluxmq
* @author: LiYuan
* @param: ipAddress
* @return: Integer
**/
public Integer getLoadInfoByIp(String ipAddress) {
int num = 0;
String URL = OnlineConstants.HTTP_PREFIX + ipAddress + OnlineConstants.FLUXMQ_INFO_URL;
OkHttpClient client = new OkHttpClient();
Request build = new Request.Builder()
.url(URL)
.get()
.addHeader("User-Agent","Apifox/1.0.0(https://apifox.com)")
.addHeader("AccessToken","")
.build();
try {
Response response = client.newCall(build).execute();
JSONArray jsonArray = JSONArray.parseArray(response.body().string());
JSONObject jsonObject = jsonArray.getJSONObject(0);
//获取mqttInfo对象的值
JSONObject mqttInfo = jsonObject.getJSONObject("mqttInfo");
//获取fluxmq链接数
num = mqttInfo.getIntValue("connectSize");
log.info("{}的fluxMq链接数为{}",ipAddress,num);
} catch (IOException e) {
log.error(e.getMessage());
}
return num;
}
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhilian.online.mapper.OnlineGatherMapper">
</mapper>