package com.wecloud.im.balance;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.wecloud.im.ws.model.WsConstants.IP_NETTY_PUBLIC;

@Component
@Slf4j
public class WsInstance {

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String addr;

    /**
     * 返回一个健康实例的公网ip
     *
     * @return
     * @throws NacosException
     */
    public String selectOneHealthyInstance() throws NacosException {
        NamingService naming = NamingFactory.createNamingService(addr);
        Instance wecloudIm = naming.selectOneHealthyInstance("wecloud_im");
        Map<String, String> metadata = wecloudIm.getMetadata();
        String publicIp = metadata.get(IP_NETTY_PUBLIC);
        log.info("get_wecloud_im_publicIp:" + publicIp);
        return publicIp;
    }

}
