用Java和DDNS将PC变成公网可访问的小型服务器(流量不限,带宽上限取决于宽带上限)

前言

其实ipv6这个我一直有断断续续的研究,因为不是主业,而且公司的网络好像不支持ipv6,所以没花多少时间研究过。

前一阵子,我有个做短视频软件的想法,就要搞个视频服务器,最初尝试了降级用网盘解决我的需求,比如特别轻量级的一个网盘,相信对个人服务器或者内网穿透有兴趣的朋友都有用过吗,Qt封装的CHFS,很小巧的软件,用来临时存取文档是没有问题,但是对视频来说,没有分片传输,导致看一个电影需要把电影整个下载下来,就很不爽。

所以准备自己写一个视频网盘,可以像百度云盘那样,点到哪个进度就看哪里,而且加载速度要快。
当然这是需求,这有个大前提,就是服务器的流量不要钱,而且带宽足够XD。

所以ipv6服务器就首先进入了我的考虑范围,ipv6不像公网ipv4需要额外申请,而且吐槽下联通这边的效率,问了两次客服,一次师傅都说不知道ipv6是啥,上次去营业厅办业务顺便问了下,也说不知道,只有企业ipv4。所以说ipv6还是方便,实际上基本上我们每个宽带都有ipv6地址,具体的可以cmd使用ipconfig看一下就可以看到,如果没有可能是没开启。
判断开没开启ipv6,CSDN博客
我浓缩精华,直接访问https://test-ipv6.com/,这个网站可以直接显示你当前电脑是否能访问ipv6。
用Java和DDNS将PC变成公网可访问的小型服务器(流量不限,带宽上限取决于宽带上限)_第1张图片
通过这个老哥的启发,想到了可以直接用ipv6

ipv6好用是好用,但是缺点就是个人ipv6地址是在不断变化的,如果能获得一个固定的网址,那访问起来就变得很容易了。

一、编写工具类

引入maven
我使用的是腾讯云的DDNS映射,主要是腾讯云的轻量服务器价格太哇塞了,家人们谁懂 XD。

        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java-common</artifactId>
            <version>LATEST</version>
        </dependency>
        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java-dnspod</artifactId>
            <version>LATEST</version>
        </dependency>

然后编写一个工具类代码

import com.ruoyi.common.core.utils.StringUtils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.dnspod.v20210323.DnspodClient;
import com.tencentcloudapi.dnspod.v20210323.models.DescribeRecordListRequest;
import com.tencentcloudapi.dnspod.v20210323.models.DescribeRecordListResponse;
import com.tencentcloudapi.dnspod.v20210323.models.ModifyRecordRequest;
import com.tencentcloudapi.dnspod.v20210323.models.ModifyRecordResponse;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * cmd提取ipv6
 * @author admin
 */
public class Ipv6Utils {

    final static String cmd = "ipconfig";

    final static String target = "IPv6 地址 . . . . . . . . . . . . :";

    final static String SecretId = "你的腾讯云DDNSDOP SecretId";

    final static String SecretKey = "你的腾讯云DDNSDOP SecretKey ";

    final static Long RecordId = 0L; //你的腾讯云DDNSDOP RecordId 

    /**
     * 获取服务所在机器ipv6
     */
    private static String getIpv6() {
        String ipv6 = StringUtils.EMPTY;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);

            BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream(),
                    System.getProperty("sun.jnu.encoding")));
            BufferedReader outputErr = new BufferedReader(new InputStreamReader(process.getErrorStream(),
                    System.getProperty("sun.jnu.encoding")));
            String line = "";
            Long l1 = 0L;
            Long l2 = 0L;
            while ((line = output.readLine()) != null) {
                l1++;
                if (line.trim().startsWith(target) && !line.contains("::")) {
                    ipv6 = line.trim().replace(target, StringUtils.EMPTY);
                }
            }
            while ((line = outputErr.readLine()) != null) {
                l2++;
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
            return ipv6;
        }
    }

    public static void updateDnsPod(){
        String ipv6 = Ipv6Utils.getIpv6();
        if(StringUtils.isNotEmpty(ipv6)){
            Ipv6Utils.updateDnsPod(ipv6);
        }
    }

    /**
     * 更新腾讯云dns
     */
    private static void updateDnsPod(String ipv6){
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(SecretId, SecretKey);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("dnspod.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            DnspodClient client = new DnspodClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            ModifyRecordRequest req = new ModifyRecordRequest();
            req.setDomain("disspua.com"); //填写你的域名
            req.setSubDomain("xxx"); //xxx.disspua.com 就是我的域名
            req.setRecordType("AAAA"); //AAAA是ipv6使用的RecordType
            req.setRecordLine("默认");
            req.setValue(ipv6); //获取到的当前ipv6地址
            req.setRecordId(RecordId);
            // 返回的resp是一个ModifyRecordResponse的实例,与请求对象对应
            ModifyRecordResponse resp = client.ModifyRecord(req);
            // 输出json格式的字符串回包
            System.out.println(ModifyRecordResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
    }

    /**
     * 获取腾讯云dns列表
     */
    private void getDnsList(){
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(SecretId, SecretKey);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("dnspod.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            DnspodClient client = new DnspodClient(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            DescribeRecordListRequest req = new DescribeRecordListRequest();
            req.setDomain("disspua.com");
            // 返回的resp是一个DescribeRecordListResponse的实例,与请求对象对应
            DescribeRecordListResponse resp = client.DescribeRecordList(req);
            // 输出json格式的字符串回包
            System.out.println(DescribeRecordListResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
    }
}

二、加入启动计划

/**
 * 网关启动程序
 * 
 * @author admin
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class GatewayApplication
{
    public static void main(String[] args)
    {
        //动态绑定ipv6
        Ipv6Utils.updateDnsPod();
        SpringApplication.run(GatewayApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙  网关启动成功   ლ(´ڡ`ლ)゙  \n" +
                "                                    _  _                                                                          \n" +
                "                                   | |(_)                                                                         \n" +
                " __      ____      ____      __  __| | _  ___  ___  _ __   _   _   __ _     ___  ___   _ __ ___                   \n" +
                " \\ \\ /\\ / /\\ \\ /\\ / /\\ \\ /\\ / / / _` || |/ __|/ __|| '_ \\ | | | | / _` |   / __|/ _ \\ | '_ ` _ \\      \n" +
                "  \\ V  V /  \\ V  V /  \\ V  V /_| (_| || |\\__ \\\\__ \\| |_) || |_| || (_| | _| (__| (_) || | | | | |          \n" +
                "   \\_/\\_/    \\_/\\_/    \\_/\\_/(_)\\__,_||_||___/|___/| .__/  \\__,_| \\__,_|(_)\\___|\\___/ |_| |_| |_|      \n" +
                "                                                   | |                                                            \n" +
                "                                                   |_|                                                            \n");
    }
}

三、结语

ok,测试用过后直接加入到网关启动类的启动命令之前,这样启动微服务的时候都会刷新DDNSDop控制台里的ipv6记录,更新为本地最新的ipv6记录,这样就可以通过域名愉快的访问服务了。
这方案好就好在,手机流量是自动走ipv6的,之前和对象想连麦看电影,都是版权限制,现在可没那些限制了,直接个人服务器走起。

你可能感兴趣的:(开源项目爬坑,java,服务器,数据库)