Springboot 使用 CacheManager(緩存是儲存到內存中去的,程序結束,緩存也沒了)


1.入口文件設置緩存注解

package com.asdphp.suddenlynlinelearningplatform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
// 開啟緩存,需要顯示的指定
@EnableCaching

public class SuddenlyNlineLearningPlatformApplication {

    public static void main(String[] args) {
        SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args);
    }

}

2.Springboot 自動裝配,在需要使用的地方

  @Autowired

  CacheManager cacheManager;
// 這里的 getCache 類似於一個 HashMap 中的一個 HashMap Key,比如這里主要緩存 短信,那么就可以分配到 aliyunMessageSendMessage 這樣一個 key 下面, 這個 key可以是任意字符串,不一定是 aliyunMessageSendMessage
Cache cache = cacheManager.getCache("aliyunMessageSendMessage");
 // 獲取緩存名 為 aliyunMessageSendMessage
            System.out.println(cache.getName());
            String code = String.valueOf(((new Random()).nextInt(999999 - 100000 + 1) + 100000));
            System.out.println(code);
// 將手機號 當作 key,驗證碼當作 value傳入
            cache.put(phone, code);
// 獲取指定手機號緩存的驗證碼
            System.out.println(cache.get(phone).get());

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM