通過jsDelivr實現Github的圖牀CDN加速

最近小夥伴們是否發現訪問我的個人博客http://xiejava.ishareread.com/圖片顯示特別快了?
我的博客的圖片是放在github上的,衆所周知的原因,github訪問不是很快,尤其是hexo博客用github做圖牀經常圖片刷不出來。一直想換圖牀,直到找到了jsDelivr,通過jsDelivr實現Github的圖牀CDN加速後果然速度快了很多。
jsdelivr是一個免費的公共CDN(內容分發網絡)服務,它允許網站開發者將他們的代碼庫、JavaScript庫、字體和其他資源託管在jsdelivr上,並通過jsdelivr的CDN網絡進行快速分發。使用jsdelivr可以有效地減少用戶下載資源的時間,提高網頁加載速度,同時減輕原始服務器的負載。
jsdelivr支持多種類型的文件託管,包括JavaScript、CSS、字體、圖片等。開發者可以將自己的文件上傳到jsdelivr,並獲取一個指向這些文件的URL。然後,他們可以在自己的網站中引用這些URL,jsdelivr會自動處理文件的緩存、分發和版本控制。
jsdelivr的優點包括:

  1. 高速分發:jsdelivr擁有全球分佈的CDN網絡,可以確保資源在全球範圍內都能快速加載。
  2. 可靠性高:jsdelivr提供了高可用性和容錯性,確保資源的穩定性和可靠性。
  3. 易於使用:開發者可以簡單地通過上傳文件或使用現有的庫來獲取資源的URL,並在網站上引用它們。
  4. 開源和免費:jsdelivr是一個開源項目,提供免費的CDN服務,對開發者非常友好。

jsdelivr的官網地址jsdelivr.com 對於gitHub的cdn加速說明如下圖所示。
gitHub的cdn加速說明

對於github的圖牀來說,要用jsdelivr的cdn加速服務很簡單
GitHub: https://<jsDelivr加速域名>/gh/<用戶>/<項目>@<版本>/<資源路徑>
github圖牀加速

拿一個實例來說明:
github的圖牀地址:https://xiejava1018.github.io/xiejavaimagesrc/images/2024/20240320/1-jsdelivr官網的github說明.png

jsdelivr的cdn加速地址爲:https://cdn.jsdelivr.net/gh/xiejava1018/xiejavaimagesrc/images/2024/20240320/1-jsdelivr官網的github說明.png

對於hexo的博客來說,就是要把原來所有在博客md文件中的github圖牀地址換成jsdelivr的cdn加速地址
寫個Python程序很容易就能完成這個工作。
代碼如下:

import os
from logutils import logging
logger=logging.getLogger(__name__)  #定義模塊日誌記錄器


# 修改替換文件內容,進行字符串替換
def changfile(blog_md_file,old_str,new_str):
    try:
        with open(blog_md_file, "r+",encoding='utf-8') as file:  # 打開文件
            contents = file.read()  # 讀取文件內容
            contents = contents.replace(old_str, new_str)  # 替換字符串
            file.seek(0)  # 定位到文件開頭
            file.write(contents)  # 將修改後的內容寫入文件
            file.truncate()  # 刪除文件剩餘部分
            logger.info(blog_md_file+'文件中的'+old_str+'已替換成'+new_str)
    except PermissionError:
        logger.error("Permission denied when trying to open the file.")
    except FileNotFoundError:
        logger.error("File not found.")
    except UnicodeDecodeError:
        logger.error("The file was not decoded correctly.")
    return None


# 讀取目錄解析md文件並進行字符串替換
def changfilebypath(filepath='',old_str='',new_str=''):
    try:
        files = os.listdir(filepath)
        for file in files:
            if file.find('.md') > 0:
                blog_file = os.path.join(filepath, file)
                changfile(blog_file,old_str,new_str)
    except FileNotFoundError as e:
        logger.error('請確認輸入是否正確!',e)



if __name__ == '__main__':
    old_img_url = 'https://xiejava1018.github.io/xiejavaimagesrc'  # Github圖牀
    new_img_url = 'https://cdn.jsdelivr.net/gh/xiejava1018/xiejavaimagesrc'  # jsdelivr加速
    changfilebypath(filepath=r'D:\CloudStation\personal\xiejavablog\myhexo\myblog\source\_posts',old_str=old_img_url,new_str=new_img_url)

作者博客:http://xiejava.ishareread.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章