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());