java-web 常见的缓存技术

96 篇文章 0 订阅
1 篇文章 0 订阅

 

使用缓存技术:对程序进行优化.

* 缓存:其实就是内存中的一块空间.可以使用缓存将数据源中的数据拿到,存入到内存中.后期获得数据的话 从缓存中进行获得.

* 常见欢送有以下几种

1.EHCache         :是Hibernate常使用的二级缓存的插件.

2.Memcache       :

3.Redis                :

        

 

ehcache

* 使用ehcache:

    * 引入jar包:

    * 引入配置文件到src目录下

 

jar包结构如图:

配置文件

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="/home/alex/tmp/ehcache"/>

	<cach
            name="categoryCache"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            />
			
	<!--
		默认缓存配置,
		以下属性是必须的:
		    name :cache的标识符,在一个CacheManager中必须唯一。
		    maxElementsInMemory : 在内存中缓存的element的最大数目。
		    maxElementsOnDisk : 在磁盘上缓存的element的最大数目。
		    eternal : 设定缓存的elements是否有有效期。如果为true,timeouts属性被忽略。
		    overflowToDisk : 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上。

		以下属性是可选的:
		    timeToIdleSeconds : 缓存element在过期前的空闲时间。
                    timeToLiveSeconds : 缓存element的有效生命期。
	            diskPersistent : 在VM重启的时候是否持久化磁盘缓存,默认是false。
		    diskExpiryThreadIntervalSeconds : 磁盘缓存的清理线程运行间隔,默认是120秒.
		    memoryStoreEvictionPolicy : 当内存缓存达到最大,有新的element加入的时候,
                    移除缓存中element的策略。默认是LRU,可选的有LFU和FIFO

	-->
</ehcache>

 

测试代码

public static void aTest() throws AddressException, MessagingException {
		//通过配置文件的流对象创建ehcache实例
		InputStream is = Test.class.getClassLoader().getResourceAsStream("ehcache.xml");
		CacheManager cm = CacheManager.create(is);
		//按cache name获得cacha
		Cache cache = cm.getCache("categoryCache");
		
		//模拟加入数据数据
		List<String> slist = new ArrayList<>();
		slist.add("a");
		slist.add("b");
		slist.add("c");
		
		cache.put(new Element("testKey", "testVal"));
		cache.put(new Element("testKey2", slist));
		
		//按key获得数据并打印
		Element element = cache.get("testKey");
		System.out.println(element.getObjectKey());
		
		Element element2 = cache.get("testKey2");
		System.out.println(element2.getObjectValue().toString());
	}

输出结果

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值