Java小强个人技术博客站点    手机版
当前位置: 首页 >> Java >> Java中使用NTP服务进行服务器校时

Java中使用NTP服务进行服务器校时

4460 Java | 2024-6-28

一、NTP 是什么?

NTP 是网络时间协议(Network Time Protocol),它用来同步网络设备【如计算机、手机】的时间的协议。

二、NTP 实现什么目的?

目的很简单,就是为了提供准确时间。因为我们的手表、手机、电脑等设备,经常会跑着跑着时间就出现了误差,或快或慢的少几秒,时间长了甚至误差过分钟。

ntp.jpg


NTP 服务器列表

Windows系统上自带的两个:time.windows.comtime.nist.gov

MacOS上自带的两个:time.apple.comtime.asia.apple.com

NTP授时快速域名服务:cn.ntp.org.cn

中国科学院国家授时中心:ntp.ntsc.ac.cn

阿里云授时服务器:ntp.aliyun.com

腾讯云授时服务器:

time1.cloud.tencent.com 

time2.cloud.tencent.com 

time3.cloud.tencent.com

time4.cloud.tencent.com

time5.cloud.tencent.com


使用Java进行对时,必须引入commons-net包

<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version> <!-- 使用你需要的最新版本 -->
</dependency>


编码非常简单,属于固定写法

package com.example.springboot.demo;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;

@Slf4j
public class NptTest {

    private static String nptUrl = "ntp.aliyun.com";
    public static void main(String[] args) {
        NTPUDPClient timeClient = new NTPUDPClient();
        try {
            // 设置超时时间为1000毫秒
            timeClient.open();
            timeClient.setDefaultTimeout(1000);
            timeClient.setSoTimeout(1000);

            // 将主机名"ntp.aliyun.com"解析为InetAddress
            InetAddress inetAddress;
            try {
                inetAddress = InetAddress.getByName(nptUrl);
            } catch (Exception e) {
                System.err.println("无法解析主机名: " + e.getMessage());
                return;
            }

            // 与阿里云NTP服务器通信
            TimeInfo timeInfo = timeClient.getTime(inetAddress);
            timeClient.close();

            // 将接收到的时间转换为Date对象
            long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
            Date time = new Date(returnTime);

            System.out.println(nptUrl + " 当前时间: " + DateUtil.formatDateTime(time));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

END

推荐您阅读更多有关于“ ntp 阿里 腾讯 授时中心 网络时间 ”的文章

下一篇:离线安装Docker和Rabbitmq

猜你喜欢

发表评论: