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());
如果觉得文章对您有帮助,希望您能 关注+推荐 哦
原文地址:https://www.cnblogs.com/xiaqiuchu/p/15088100.html