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 方法测试缓存是否成功

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加 Ehcache 依赖 在 Maven 添加 Ehcache 的依赖: ```xml <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.8.1</version> </dependency> ``` 2. 创建 Ehcache 配置文件 在项目的 classpath 下创建 Ehcache 的配置文件 ehcache.xml,配置缓存策略和缓存区域。 示例: ```xml <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <cache alias="userCache"> <key-type>java.lang.String</key-type> <value-type>com.example.User</value-type> <expiry> <ttl unit="seconds">60</ttl> <tti unit="seconds">30</tti> </expiry> <resources> <heap unit="entries">100</heap> <offheap unit="MB">10</offheap> </resources> </cache> </config> ``` 3. 配置 Ehcache 缓存管理器 在 Spring Boot ,可以通过注解 @EnableCaching 和 @Configuration 注解来配置 Ehcache 缓存管理器。 示例: ```java @Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { Resource resource = new ClassPathResource("ehcache.xml"); Configuration configuration = ConfigurationFactory.parseConfiguration(resource.getInputStream()); return CacheManagerBuilder.newCacheManagerBuilder() .withCache("userCache", UserCacheConfigurationBuilder.newUserCacheConfigurationBuilder().buildConfig(String.class, User.class)) .withCache("bookCache", BookCacheConfigurationBuilder.newBookCacheConfigurationBuilder().buildConfig(Long.class, Book.class)) .withConfiguration(configuration) .build(true); } } ``` 4. 使用 Ehcache 缓存管理器 在需要使用缓存的方法上添加 @Cacheable、@CachePut 或 @CacheEvict 注解来实现缓存的读取、写入和删除。 示例: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "userCache", key = "#id") public User getUserById(String id) { return userRepository.findById(id).orElse(null); } @CachePut(value = "userCache", key = "#user.id") public User saveOrUpdateUser(User user) { return userRepository.save(user); } @CacheEvict(value = "userCache", key = "#id") public void deleteUserById(String id) { userRepository.deleteById(id); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值