package com.yh.tg.sys.configcache;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSON;
import com.yh.tg.basic.utils.LogUtils;
import com.yh.tg.config.OkhttpUtils;
import com.yh.tg.sys.utils.JsonUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class GetUrlUtil {
    private static OkHttpClient client = OkhttpUtils.okHttpClient();

    public static String serverPort;
    public static String httpUrl;
    @Value("${server.port}")
    private String port;
    @Value("${spring.profiles.active}")
    private String active;

    @PostConstruct
    public void setServerPort(){
        this.serverPort= port;
        StaticLog.info("port:"+this.serverPort);
        if(StrUtil.equals(this.active,"test")){
            httpUrl = getUrl();
        }else {
            httpUrl = getIpv4();
        }
    }

    //如果是本地测试环境返回本地ip  如果是网络测试环境返回外网ip
    /**
     * 获取当前服务的内网ip和端口
     * @return
     */
    public static String getUrl() {

        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch ( UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress() +":"+ GetUrlUtil.serverPort+"/";
    }

    /**
     *获取当前服务的外网ip和端口
     */
    public static String getIpv4() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch ( UnknownHostException e) {
            e.printStackTrace();
        }
        String v4IP = "";
        while (StrUtil.isBlank(v4IP)){
            LogUtils.error("获取外网IP失败,正在重试");
            v4IP = getV4IP();
        }
        LogUtils.info("获取外网IP成功");
        return "http://"+v4IP+":"+ GetUrlUtil.serverPort+"/";
    }

    public static String getV4IP(){
        String ip = "";
        String url = "https://api.live.bilibili.com/client/v1/Ip/getInfoNew";
        Request request = new Request.Builder().url(url).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if(ObjectUtil.isNotNull(response)){
                String data =  response.body().string();
                Object succesResponse = JSON.parse(data);
                ip = JsonUtils.getValueByKey(succesResponse, "addr").toString();
            }
        } catch (Exception e) {
            System.err.println(e);
            ip="";
        }
        return ip;
    }

}

上一篇 下一篇