1. 程式人生 > >EhCache教程之Hello World和與Spring整合

EhCache教程之Hello World和與Spring整合

一:目錄

  • EhCache 簡介
  • Hello World 示例
  • Spring 整合

二: 簡介

1. 基本介紹

EhCache 是一個純Java的程序內快取框架,具有快速、精幹等特點,是Hibernate中預設CacheProvider。Ehcache是一種廣泛使用的開源Java分散式快取。主要面向通用快取,Java EE和輕量級容器。它具有記憶體和磁碟儲存,快取載入器,快取擴充套件,快取異常處理程式,一個gzip快取servlet過濾器,支援REST和SOAP api等特點。

Spring 提供了對快取功能的抽象:即允許繫結不同的快取解決方案(如Ehcache),但本身不直接提供快取功能的實現。它支援註解方式使用快取,非常方便。

2. 主要的特性有:

  1. 快速
  2. 簡單
  3. 多種快取策略
  4. 快取資料有兩級:記憶體和磁碟,因此無需擔心容量問題
  5. 快取資料會在虛擬機器重啟的過程中寫入磁碟
  6. 可以通過RMI、可插入API等方式進行分散式快取
  7. 具有快取和快取管理器的偵聽介面
  8. 支援多快取管理器例項,以及一個例項的多個快取區域
  9. 提供Hibernate的快取實現

3. 整合

可以單獨使用,一般在第三方庫中被用到的比較多(如mybatis、shiro等)ehcache 對分散式支援不夠好,多個節點不能同步,通常和redis一塊使用

4. ehcache 和 redis 比較

  • ehcache直接在jvm虛擬機器中快取,速度快,效率高;但是快取共享麻煩,叢集分散式應用不方便。

  • redis是通過socket訪問到快取服務,效率比ecache低,比資料庫要快很多,
    處理叢集和分散式快取方便,有成熟的方案。如果是單個應用或者對快取訪問要求很高的應用,用ehcache。如果是大型系統,存在快取共享、分散式部署、快取內容很大的,建議用redis。

ehcache也有快取共享方案,不過是通過RMI或者Jgroup多播方式進行廣播快取通知更新,快取共享複雜,維護不方便;簡單的共享可以,但是涉及到快取恢復,大資料快取,則不合適。


三: Hello World

1、在pom.xml中引入依賴

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

2、在src/main/resources/建立一個配置檔案 ehcache.xml

預設情況下Ehcache會自動載入classpath根目錄下名為ehcache.xml檔案,也可以將該檔案放到其他地方在使用時指定檔案的位置

<?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"/>

  <!-- 預設快取 -->
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
  </defaultCache>

  <!-- helloworld快取 -->
  <cache name="HelloWorldCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="5"
         timeToLiveSeconds="5"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>

3、測試類

package com.mengdee.manage.cache;

import com.mengdee.manage.entity.Dog;

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

public class CacheTest {

    public static void main(String[] args) {

        // 1. 建立快取管理器
        CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");

        // 2. 獲取快取物件
        Cache cache = cacheManager.getCache("HelloWorldCache");

        // 3. 建立元素
        Element element = new Element("key1", "value1");

        // 4. 將元素新增到快取
        cache.put(element);

        // 5. 獲取快取
        Element value = cache.get("key1");
        System.out.println(value);
        System.out.println(value.getObjectValue());

        // 6. 刪除元素
        cache.remove("key1");

        Dog dog = new Dog(1L, "taidi", (short)2);
        Element element2 = new Element("taidi", dog);
        cache.put(element2);
        Element value2 = cache.get("taidi");
        Dog dog2 = (Dog) value2.getObjectValue();
        System.out.println(dog2);

        System.out.println(cache.getSize());

        // 7. 重新整理快取
        cache.flush();

        // 8. 關閉快取管理器
        cacheManager.shutdown();
    }
}

4、快取配置

一:xml配置方式:

  • diskStore : ehcache支援記憶體和磁碟兩種儲存

    • path :指定磁碟儲存的位置
  • defaultCache : 預設的快取

    • maxEntriesLocalHeap=”10000”
    • eternal=”false”
    • timeToIdleSeconds=”120”
    • timeToLiveSeconds=”120”
    • maxEntriesLocalDisk=”10000000”
    • diskExpiryThreadIntervalSeconds=”120”
    • memoryStoreEvictionPolicy=”LRU”
  • cache :自定的快取,當自定的配置不滿足實際情況時可以通過自定義(可以包含多個cache節點)

    • name : 快取的名稱,可以通過指定名稱獲取指定的某個Cache物件

    • maxElementsInMemory :記憶體中允許儲存的最大的元素個數,0代表無限個

    • clearOnFlush:記憶體數量最大時是否清除。

    • eternal :設定快取中物件是否為永久的,如果是,超時設定將被忽略,物件從不過期。根據儲存資料的不同,例如一些靜態不變的資料如省市區等可以設定為永不過時

    • timeToIdleSeconds : 設定物件在失效前的允許閒置時間(單位:秒)。僅當eternal=false物件不是永久有效時使用,可選屬性,預設值是0,也就是可閒置時間無窮大。

    • timeToLiveSeconds :快取資料的生存時間(TTL),也就是一個元素從構建到消亡的最大時間間隔值,這隻能在元素不是永久駐留時有效,如果該值是0就意味著元素可以停頓無窮長的時間。

    • overflowToDisk :記憶體不足時,是否啟用磁碟快取。

    • maxEntriesLocalDisk:當記憶體中物件數量達到maxElementsInMemory時,Ehcache將會物件寫到磁碟中。

    • maxElementsOnDisk:硬碟最大快取個數。

    • diskSpoolBufferSizeMB:這個引數設定DiskStore(磁碟快取)的快取區大小。預設是30MB。每個Cache都應該有自己的一個緩衝區。

    • diskPersistent:是否在VM重啟時儲存硬碟的快取資料。預設值是false。

    • diskExpiryThreadIntervalSeconds:磁碟失效執行緒執行時間間隔,預設是120秒。

二:程式設計方式配置

Cache cache = manager.getCache("mycache"); 
CacheConfiguration config = cache.getCacheConfiguration(); 
config.setTimeToIdleSeconds(60); 
config.setTimeToLiveSeconds(120); 
config.setmaxEntriesLocalHeap(10000); 
config.setmaxEntriesLocalDisk(1000000);

5、Ehcache API

  • CacheManager:Cache的容器物件,並管理著(新增或刪除)Cache的生命週期。
// 可以自己建立一個Cache物件新增到CacheManager中
public void addCache(Cache cache);
public synchronized void removeCache(String cacheName);
  • Cache: 一個Cache可以包含多個Element,並被CacheManager管理。它實現了對快取的邏輯行為

  • Element:需要快取的元素,它維護著一個鍵值對, 元素也可以設定有效期,0代表無限制

  • 獲取CacheManager的方式:

    可以通過create()或者newInstance()方法或過載方法來建立獲取CacheManager的方式:

public static CacheManager create();
public static CacheManager create(String configurationFileName);
public static CacheManager create(InputStream inputStream);
public static CacheManager create(URL configurationFileURL);

public static CacheManager newInstance();

Ehcache的CacheManager建構函式或工廠方法被呼叫時,會預設載入classpath下名為ehcache.xml的配置檔案。
如果載入失敗,會載入Ehcache jar包中的ehcache-failsafe.xml檔案,這個檔案中含有簡單的預設配置。

// CacheManager.create() == CacheManager.create("./src/main/resources/ehcache.xml")
// 使用Ehcache預設配置新建一個CacheManager例項
CacheManager cacheManager = CacheManager.create();
cacheManager = CacheManager.newInstance();

cacheManager = CacheManager.newInstance("./src/main/resources/ehcache.xml");

InputStream inputStream = new FileInputStream(new File("./src/main/resources/ehcache.xml"));
cacheManager = CacheManager.newInstance(inputStream);

String[] cacheNames = cacheManager.getCacheNames();  // [HelloWorldCache]

四:Spring整合

示例結構:

這裡寫圖片描述

1. pom.xml 引入spring和ehcache

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mengdee</groupId>
  <artifactId>ehcache</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>4.10</junit.version>
    <spring.version>4.2.3.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-test</artifactId>
         <version>${spring.version}</version>
         <scope>test</scope>
     </dependency>


    <!-- springframework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

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


  </dependencies>

  <repositories>
    <repository>
        <id>aliyun</id>
        <name>aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </repository>
  </repositories>
</project>

2. 在src/main/resources新增ehcache.xml

<?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" />

  <!-- 預設快取 -->
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
  </defaultCache>

  <!-- helloworld快取 -->
  <cache name="HelloWorldCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="5"
         timeToLiveSeconds="5"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>

  <cache name="UserCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="1800"
         timeToLiveSeconds="1800"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>

3. 在src/main/resources/conf/spring中配置spring-base.xml和spring-ehcache.xml

spring-base.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="com.mengdee.**.dao,com.mengdee.**.service"/>
</beans>

spring-ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">

  <description>ehcache快取配置管理檔案</description>

  <!-- 啟用快取註解開關 -->
  <cache:annotation-driven cache-manager="cacheManager"/>

  <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="ehcache"/>
  </bean>

  <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
  </bean>

</beans>

4、在src/main/java/com.mengdee.manager.service/下 建立EhcacheService和EhcacheServiceImpl

EhcacheService

package com.mengdee.manager.service;

import com.mengdee.manager.entity.User;

public interface EhcacheService {

    // 測試失效情況,有效期為5秒
    public String getTimestamp(String param);

    public String getDataFromDB(String key);

    public void removeDataAtDB(String key);

    public String refreshData(String key);


    public User findById(String userId);

    public 
            
           

相關推薦

EhCache教程Hello WorldSpring整合

一:目錄 EhCache 簡介 Hello World 示例 Spring 整合 二: 簡介 1. 基本介紹 EhCache 是一個純Java的程序內快取框架,具有快速、精幹等特點,是Hibernate中預設Cache

c++ 入門 hello world 基本語法

安裝 變量類型 double 自己 表示 visual gcc 理解 定義 1,linux系統上如何跑c++程序 1,vim一個hello.cpp,內容如下: #include <iostream> using namespace std; int m

Spring BootHello World

lns mode mls compile ase closed amp 創建 AC 通過Spring Boot【1.5.11.RELEASE】 官方文檔進行學習,並記錄一點一滴的成長。 Spring Boot 簡介對於Spring可以輕松地創建獨立的、生產級的Spri

spring boot hello world

clas 開發 r文件 rate 第一次 framework localhost 運行 urn 這是自娛自樂的隨筆系列,可能還帶抄襲,因為我是0基礎,然後引用的地方我也會給出參考地址: 話不多說,先搞個官網給的demo之 hello world 開發工具使用:IDEA,這個

譯: 1. RabbitMQ Spring AMQP Hello World

lock tutorials -s 消費者 spa 發送 等待 編輯器 緩沖 本文是譯文,原文請訪問:http://www.rabbitmq.com/tutorials/tutorial-one-spring-amqp.html RabbitMQ 是一個Brocker (消

Spring Boot 2.0 Hello World

    Spring Boot 簡化了 Spring 的操作, 不需要配置就能執行 Spring 應用. Spring Boot 管理 spring 容器、第三方外掛, 並提供很多預設系統級的服務. Spring Boot 通過 Starter 來提供系統級服務. 

SpringHELLO WORLD

Ioc和DI介紹     HELLO WORLD程式           getBean方法的三種簽名 解決方案:    

RabbitMQ Hello World 工作佇列 (一)

<dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <vers

Spring Boothello world”!

前言 spring boot出來已經很長一段時間了,一直以來都只是聽周邊的朋友說,這個框架很簡單、方便、快捷。但我也沒有抽時間去研究和使用過它。現在spring boot都已經出到了2.0以上的版本了,我自己也覺得,再不去學,就要與主流脫節了,所有趕緊抽出點個人時間,在

使用Maven構建Spring Boot 第一課Hello world 程式

Spring Boot 學習第一課 準備開始 JDK1.8 + Gradle 2.3+ or Maven 3.0+ IDE Spring Tool Suite (STS) https://spring.io/tools/sts/ I

Spring Boot學習入門Hello World(一)

1.通過Spring Initializr(地址:http://start.spring.io/)生成Spring Boot專案結構 2.匯入Spring Boot專案 pom.xml內容: 3.編寫RESTful API 4.啟動Spring Boot應用 三

JAVAWEB開發mybatis詳解(二)——高階對映、查詢快取、mybatisSpring整合以及懶載入的配置逆向工程

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "ht

Spring boot 學習 Hello World

使用IDE新建maven專案,如果使用eclipse,則選擇jar包方式(不選擇war包方式) 必須要引入繼承springboot-parent包,它幫我們實現了很多jar的依賴管理(這個在<d

spring-boot初體驗hello world

spring-boot 框架入門例項記錄 環境: jdk8環境已部署 maven環境已部署 sts工具(spring官網可下載)  筆者用的是windows平臺  建立springboot的方法有很多種,筆者選擇最簡單的方式,使用sts中自帶的建立方法,如下示意

C#開發Unity遊戲教程Scene視圖腳本的使用

ont 展開 支持 查看 提示 microsoft etime font 一個 C#開發Unity遊戲教程之Scene視圖與腳本的使用 Unity中Scene視圖的快捷操作 Scene視圖是開發人員開發遊戲時,操作最頻繁的視圖。由於一旦一個遊戲對象被加入到遊戲的場

56.storm hello world (集群模式)

目錄 是否 代碼 -1 maven 參考 ntb 分享 log文件 回顧   在上一小節,我們在PWTopology1 這一個java類中註解掉了集群模式,使用本地模式大概了解一下storm的工作流程。這一節我們註解掉本地模式相關的代碼,放開集群模式相關代碼,並且將項目打包

Android NDK Hello World

module path package ren ide string style activity code 首先編寫Jni接口的c文件,此文件命名有些特殊,具體的命名方式可以參考文檔來做。 #include <jni.h> #include <stri

Intellij idea史上最簡單的教程Linux下安裝破解Intellij idea2017

成功 zxvf java 新建 pre form 旗艦版 lan intel 一、前言 這一節我們介紹在Linux下如何安裝與破解Intellij idea2017。現在有很多公司開發環境都是Linux,所以掌握在Linux環境下使用Idea辦公也是咱們必須得掌握的技能。

ExpressHello World示例

req rip exp cti world! post url send 字符串 接前文: node.js安裝應用手記 Express安裝過程 接下來,我們一起創建一個基本的 Express 應用。 註意:這裏所創建是一個最最簡單的 Express 應用,並且僅僅只有一

SpringMVC系列(十五)Spring MVCSpring整合時實例被創建兩次的解決方案以及Spring 的 IOC 容器 SpringMVC 的 IOC 容器的關系

問題 nbsp frame ota 展示 not als pri exc 一、Spring MVC與Spring整合時實例被創建兩次的解決方案 1.問題產生的原因 Spring MVC的配置文件和Spring的配置文件裏面都使用了掃描註解<context:compon