日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Springboot實現緩存預熱

作者:Spirit_NKlaus 更新時間: 2024-03-06 編程語言

很多時候我們代碼中使用緩存時都是先判斷緩存中沒有數據我們再讀取數據庫而有則直接使用緩存數據,而在系統冷啟動(當系統重啟或新啟動時,緩存是空的,這被稱為冷啟動)時,我們毫無意外都是直接獲取數據庫的內容,這時候緩存的命中率幾乎為0,這時候我們需要考慮業務系統的緩存預熱功能,在系統啟動之前通過預先將常用數據加載到緩存中,以提高緩存命中率和系統性能的過程。緩存預熱的目的是盡可能地避免緩存擊穿和緩存雪崩。

一、系統啟動時加載
1、CommandLineRunner和ApplicationRunner是SpringBoot中用于在應用程序啟動后執行特定邏輯的接口。

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 緩存預熱器(CommandLineRunner方式)
 */
@Component
@Slf4j
public class CacheCLRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        //TODO 緩存預熱邏輯
        log.info("CommandLineRunner方式完成緩存預熱");
    }
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 緩存預熱器(ApplicationRunner方式)
 */
@Component
@Slf4j
public class CacheAppRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //TODO 緩存預熱邏輯
        log.info("ApplicationRunner方式完成緩存預熱");
    }
}

2、實現InitializingBean接口,并在afterPropertiesSet方法中執行緩存預熱的邏輯。這樣Spring在初始化Bean時會調用afterPropertiesSet方法

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 緩存預熱器(InitializingBean方式)
 */
@Component
@Slf4j
public class CacheInitializing implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        //TODO 緩存預熱邏輯
        log.info("InitializingBean方式完成緩存預熱");
    }
}


3、基于ApplicationReadyEvent,我們可以在應用程序完全啟動并處于可用狀態后執行一些初始化邏輯。使用@EventListener注解或實現ApplicationListener接口來監聽這個事件。
4、@PostConstruct注解標注一個方法,該方法將在 Bean 的構造函數執行完畢后立即被調用。
這里3、4點的例子寫在一起

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 緩存預熱器(ApplicationReadyEvent和@PostConstruct方式)
 */
@Component
@Slf4j
public class CacheLoader {

    @EventListener(ApplicationReadyEvent.class)
    public void loadCache1() {
        //TODO 緩存預熱邏輯
        log.info("@EventListener方式完成緩存預熱");
    }

    @PostConstruct
    public void loadCache2() {
        //TODO 緩存預熱邏輯
        log.info("@PostConstruct方式完成緩存預熱");
    }
}

啟動項目大致看一下4種方式的加載順序,可根據自己的需求選擇對應的方式
?

二、定時任務加載
使用Spring的@Scheduled,quartz,xxl-job都可以,@Scheduled為例

@Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1點執行
public void scheduledCachePreload() {
	//TODO 緩存預熱邏輯
	log.info("定時任務方式完成緩存預熱");
}

原文鏈接:https://blog.csdn.net/LittleMangoYX/article/details/136447593

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新