Springboot2.x 使用 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());
复制代码

 

posted @   夏秋初  阅读(1210)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示