package com.muyu.cargateway.instance;

import com.muyu.cargateway.Aliyun.service.AliYunEcsService;
import com.muyu.cargateway.config.AliProperties;
import com.muyu.cargateway.domain.AliInstance;
import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Lenovo
 * @ Tool：IntelliJ IDEA
 * @ Author：CHX
 * @ Date：2024-09-28-21:10
 * @ Version：1.0
 * @ Description：调用ali的类
 */
@Log4j2
@Component
public class Sample implements ApplicationRunner{

    @Autowired
    private AliYunEcsService aliYunEcsService;
    @Autowired
    private AliProperties aliProperties;
    @Autowired
    private RedisService redisService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> list;
        try {
            log.info("开始创建实例");
            list = aliYunEcsService.generateInstance(aliProperties.getAmount());
        } catch (Exception e) {
            log.info("创建实例失败");
            throw new RuntimeException(e);
        }
        log.info("创建实例成功");
        redisService.setCacheList("instanceIds", list);
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        List<AliInstance> aliInstances = aliYunEcsService.selectInstance(list);
        log.info("查询实例信息成功：{}",aliInstances);
        // 将查询到的实例信息列表存储到Redis中
        redisService.setCacheList("instanceList", aliInstances);
        log.info("redis存储成功：{}", aliInstances);
    }

//    @Override
//    public void destroy(){
//        try {
//            log.info("===开始执行删除实例方法");
//            aliYunEcsService.deleteInstance();
//            redisService.deleteObject("instanceIds");
//            redisService.deleteObject("instanceList");
//        } catch (Exception e) {
//            log.info("删除实例失败");
//            throw new RuntimeException(e);
//        }
//        log.info("删除实例成功");
//    }
}
