Spring Boot Cache构建缓存

第一步 引入依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

第二步 创建缓存配置类

@Configuration
public class SpringCachingConfig {

    /**
     * 定义和配置缓存管理器
     * 
     * @return 配置好的 CacheManager 实例
     */
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        Set<ConcurrentMapCache> mapCaches = new HashSet<ConcurrentMapCache>();
        // 配置缓存名称和类型
        mapCaches.add(new ConcurrentMapCache(CacheNameConst.Jw_Amdin_Menu)); // 这里就是将缓存器的名称添加进去
        mapCaches.add(new ConcurrentMapCache(CacheNameConst.Jw_Amdin_Dict));
        mapCaches.add(new ConcurrentMapCache(CacheNameConst.Jw_Amdin_Log));
        mapCaches.add(new ConcurrentMapCache(CacheNameConst.Jw_Amdin_User));
        mapCaches.add(new ConcurrentMapCache(CacheNameConst.OSS));
        cacheManager.setCaches(mapCaches);
        cacheManager.afterPropertiesSet();
        return cacheManager;
    }
}

第三步 可以创建一些静态的缓存器名称(创建CacheNameConst类)

public class CacheNameConst {
	/**
	 *  菜单/权限
	 */
	public static String Jw_Amdin_Menu="Jw_amdin_menu";
	/**
	 * 数据字典
	 */
    public static String Jw_Amdin_Dict="Jw_amdin_dict";
    /**
     * 系统日志
     */
    public static String Jw_Amdin_Log="Jw_amdin_log";
    /**
     * 系统用户
     */
    public static String Jw_Amdin_User="Jw_amdin_user";

	public static String OSS="OSS";
}

第四步 编写缓存的工具类,以后用缓存的方法都可以从里面直接调用

/**
 *
 */
package com.zhangru.rzy.admin.api.config.cache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;

/**
 * 本地缓存工具类
 * @author 楠Zz
 * @date: 2024/09/9 11:55
 *
 */
@Component
public class CacheUtil {


	private Logger logger = LoggerFactory.getLogger(CacheUtil.class);

	@Autowired
    private CacheManager cacheManager;


    private static CacheManager cm;

    @PostConstruct
    public void init() {
        cm = cacheManager;
    }

    /**
     * 添加缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     * @param value     缓存值
     */
    public  void put(String cacheName, String key, Object value) {
        Cache cache = cm.getCache(cacheName);
        cache.put(key, value);
    }

    /**
     * 获取缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     * @return
     */
    public  Object get(String cacheName, String key) {
        try {
			Cache cache = cm.getCache(cacheName);
			if (cache == null) {
			    return null;
			}
			if(null != cache.get(key)){
				ValueWrapper valueWrapper=cache.get(key);
				if(null != valueWrapper){
					return valueWrapper.get();
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(e.getMessage(), e);
			return null;
		}
        return null;
    }

    /**
     * 获取缓存(字符串)
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     * @return
     */
    public  String getString(String cacheName, String key) {
        Cache cache = cm.getCache(cacheName);
        if (cache == null) {
            return null;
        }
        Cache.ValueWrapper wrapper = cache.get(key);
        if (wrapper == null) {
            return null;
        }
        try {
        	if(null != wrapper.get()){
            	return Objects.requireNonNull(wrapper.get()).toString();
            }
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
        return null;
    }

    /**
     * 获取缓存(泛型)
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     * @param clazz     缓存类
     * @param <T>       返回值泛型
     * @return
     */
    @SuppressWarnings("unchecked")
	public  <T> T get(String cacheName, String key, Class<T> clazz) {
        Cache cache = cm.getCache(cacheName);
        if (cache == null) {
            return null;
        }
        Cache.ValueWrapper wrapper = cache.get(key);
        if (wrapper == null) {
            return null;
        }
        return (T) wrapper.get();
    }

    /**
     * 失效缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     */
    public  void evict(String cacheName, String key) {
        Cache cache = cm.getCache(cacheName);
        if (cache != null) {
            cache.evict(key);
        }
    }
}

第五步 直接使用(使用案例)


查看控制台打印日志

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值