springboot 项目中配置缓存

tip:配置缓存 提高系统的性能

一:在pom 文件中加入依赖

	    <dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>

二:缓存的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

	<!-- 磁盘缓存位置 -->
	<diskStore path="java.io.tmpdir/ehcache" />
	<!-- 默认缓存 -->
	<!-- timeToIdleSeconds:置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 -->
	<!-- timeToLiveSeconds:缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。 -->
	<!-- maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 -->
	<!-- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 -->
	<!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 -->
	<!-- 默认缓存 -->
	<defaultCache maxEntriesLocalHeap="10000" eternal="false"
		timeToIdleSeconds="600" timeToLiveSeconds="600" maxEntriesLocalDisk="10000000"
		diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

	<!-- FinalPartInfoUtil工具类的缓存 -->
	<cache name="User" maxElementsInMemory="10000"
		eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="600"
		overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />

	<cache name="UserLogin" maxElementsInMemory="10000"
		   eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="600"
		   overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />

	<cache name="WinRecord" maxElementsInMemory="10000"
		   eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="600"
		   overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />
</ehcache>

描述:要配置缓存的名称user等

三:编写缓存的工具类 EHCacheUtil

package com.hyhh.microcloud.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.util.List;

/**
 * CREATED BY IDEA
 *
 * @Author taojun
 * @Date 2019/3/289:09
 * @VERSION 1.0
 * @COMPANY HLXD
 * @PROJECT hyhhmicrocloud
 */
public class EHCacheUtil {
    /**
     * 缓存管理器
     */
    private static CacheManager cacheManager;

    private EHCacheUtil() {
        // 私有化构造方法
    }

    // 静态代码块,保证singleton。
    static {
        cacheManager = CacheManager.create();
    }

    /**
     * 根据缓存名字获得某个缓存
     *
     * @param cacheName
     * @return
     */
    public static Cache getCache(String cacheName) {
        return cacheManager.getCache(cacheName);
    }

    /**
     * 根据缓存名字,元素的key值,获得缓存中对应的value值对象。
     *
     * @param cacheName
     * @param key
     * @param isRemoveKey
     * @return
     */
    public static Object getValue(String cacheName, Object key,
                                  boolean isRemoveKey) {
        Cache cache = getCache(cacheName);
        Element e = null;
        if (isRemoveKey) {
            e = cache.get(key);
        } else {
            e = cache.getQuiet(key);
        }
        if (e == null) {
            return null;
        }
        return e.getObjectValue();
    }

    /**
     * 根据缓存名字,元素的key值,获得缓存中对应的value值对象。
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Object getValue(String cacheName, Object key) {
        return getValue(cacheName, key, false);
    }

    /**
     * 静态的获取元素,不会产生update.
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Element getElementByQuite(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        return cache.getQuiet(key);
    }

    /**
     * 动态的获取元素,会产生update.
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Element getElementByDynic(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        return cache.get(key);
    }

    /**
     * 向某个缓存中添加元素
     *
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, Object key, Object value) {
        Element element = new Element(key, value);
        getCache(cacheName).put(element);
    }

    /**
     * 移除某个缓存中的元素
     *
     * @param cacheName
     * @param key
     */
    public static void remove(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        if (cache != null) {
            cache.remove(key);
        }
    }

    /**
     * 移除某个缓存中所有的元素
     *
     * @param cacheName
     */
    public static void removeAll(String cacheName) {
        Cache cache = getCache(cacheName);
        if (cache != null) {
            for (Object object : cache.getKeys()) {
                cache.remove(object);
            }
        }
    }

    /**
     * 判断某个缓存是否包含某个元素
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static boolean contains(String cacheName, Object key) {
        Cache cache = getCache(cacheName);
        Element e = cache.get(key);
        if (e != null) {
            return true;
        }
        return false;
    }

    /**
     * 获取某个缓存中所有的key
     *
     * @param cacheName
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> getKeys(String cacheName, Class<T> t) {
        Cache cache = getCache(cacheName);
        return (List<T>) cache.getKeys();
    }

    public static void main(String[] args) {
        String key = "hello";
        String value = "world";
        EHCacheUtil.put("articleCache", key, value);
        System.out.println(EHCacheUtil.getValue("articleCache", key));
    }
}

四:main 方法测试缓存是否成功

发布了75 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/zy1471162851/article/details/90754062