ehcache3 简单使用

版权声明:本文为博主原创文章,未经允许不得转发 https://blog.csdn.net/fengchen0123456789/article/details/84642908

maven

    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>3.6.2</version>
    </dependency>

代码

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;

import java.util.concurrent.TimeUnit;

/**
 * @author lf
 * @描述 测试ehcache缓存
 * @date 2018-11-27
 */
public class EhcacheTest {

    public static void main(String[] args) {
        // 构建一个缓存管理器
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true);

        CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder
                .newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(10000))
                // 存活时间是3秒,过期后自动清除
                .withExpiry(Expirations.timeToLiveExpiration(Duration.of(3, TimeUnit.MINUTES))).build();
        // 根据配置创建一个缓存容器
        Cache<String, String> myCache = cacheManager.createCache("myCache", cacheConfiguration);
        // 设置一个值
        myCache.put("key", "value");

        try {
            Thread.sleep(1000);
            System.out.println("yi:"+myCache.get("key"));

            Thread.sleep(1000);
            System.out.println("er:"+myCache.get("key"));

            myCache.put("key", "value");

            Thread.sleep(1000);
            System.out.println("san:"+myCache.get("key"));

            Thread.sleep(1000);
            System.out.println("si:"+myCache.get("key"));

            Thread.sleep(1000);
            System.out.println("wu:"+myCache.get("key"));

            Thread.sleep(1000);
            System.out.println("liu:"+myCache.get("key"));

            Thread.sleep(1000);
            System.out.println("qi:"+myCache.get("key"));

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        cacheManager.close();
    }
}

容器可以创建多个,经测试,重新添加已经存在的key,它的过期时间是重新计算,过期就自动删除了,获取出来的值就是null

官网 http://www.ehcache.org/documentation/

展开阅读全文

没有更多推荐了,返回首页