package com.springboot.cloud.sysadmin.organization.config;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2020-12-24          FXY        Created
 **********************************************
 */

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.Set;

@Configuration
@Slf4j
public class NacosRegisterConfig implements ApplicationRunner {

    @Autowired(required = false)
    private NacosAutoServiceRegistration registration;

    private Integer port;

    public NacosRegisterConfig() {
        try {
            this.port = Integer.parseInt(getTomcatPort());
        } catch (Exception e) {
            log.error("获取tomcat端口出错了，原因：{}", e.toString());
        }
    }

    @Override
    public void run(ApplicationArguments args) {
        if (registration != null && port != null) {
            registration.setPort(port);
            registration.start();
        }
    }

    //获取tomcat端口
    private String getTomcatPort() throws Exception {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
        String port = objectNames.iterator().next().getKeyProperty("port");
        return port;
    }

}
