Springboot整合ehcache緩存


EhCache是一個比較成熟的Java緩存框架,最早從hibernate發展而來, 是進程中的緩存系統,它提供了用內存,磁盤文件存儲,以及分布式存儲方式等多種靈活的cache管理方案,快速簡單。

Springboot對ehcache的使用非常支持,所以在Springboot中只需做些配置就可使用,且使用方式也簡易。

在你的項目上配置以下幾步即可使用

首先,老規矩,pom.xml加依賴;

		<!-- Spring Boot 緩存支持啟動器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<!-- Ehcache 坐標 -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>

第二步,創建ehcache.xml配置文件

位置:classpath目錄下,即src/main/resources/ehcache.xml

文件內容開發的時候可參考第一步導入的jar包,具體在哪呢,看下面:

再看代碼:

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

    <diskStore path="java.io.tmpdir"/>

  <!--defaultCache:echcache的默認緩存策略  -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <cache name="users"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

 說明:

<diskStore path="java.io.tmpdir"/>這個是磁盤存儲路徑,當內存緩存滿了的時候,就會往這里面放,java.io.tmdir是操作系統緩存的臨時目錄,不同操作系統緩存目錄不一樣。
maxElementsInMemory      內存緩存中最多可以存放的元素數量,若放入Cache中的元素超過這個數值,則有以下兩種情況  
                         1)若overflowToDisk=true,則會將Cache中多出的元素放入磁盤文件中  
                         2)若overflowToDisk=false,則根據memoryStoreEvictionPolicy策略替換Cache中原有的元素
overflowToDisk           內存不足時,是否啟用磁盤緩存
eternal                  緩存中對象是否永久有效
timeToIdleSeconds        緩存數據在失效前的允許閑置時間(單位:秒),僅當eternal=false時使用,默認值是0表示可閑置時間無窮大,若超過這個時間沒有訪問此Cache中的某個元素,那么此元素將被從Cache中清除
timeToLiveSeconds        緩存數據的總的存活時間(單位:秒),僅當eternal=false時使用,從創建開始計時,失效結束。
maxElementsOnDisk        磁盤緩存中最多可以存放的元素數量,0表示無窮大
diskExpiryThreadIntervalSeconds   磁盤緩存的清理線程運行間隔,默認是120秒
memoryStoreEvictionPolicy   內存存儲與釋放策略,即達到maxElementsInMemory限制時,Ehcache會根據指定策略清理內存  共有三種策略,分別為LRU(最近最少使用)、LFU(最常用的)、FIFO(先進先出)

另外,defaultCache是默認緩存方式,cache是自定義的緩存方式,自行設置name


第三步,在Springboot配置文件中把ehcache.xml配置進去;即在application.properties中加入以下配置代碼
spring.cache.ehcache.config=ehcache.xml

 

第三步結束,ehcache在Springboot中就配置完成了,下面就是怎么在Springboot中使用

第四步,在啟動類前加上@EnableCaching注解;這樣的話,啟動類啟動時會去啟動緩存啟動器。

@SpringBootApplication
@MapperScan("com.yunxing.mapper")
@EnableCaching
public class app {

	public static void main(String[] args) {
		SpringApplication.run(app.class, args);

	}

}

  第五步,實體類實現可序列化接口Serializable;由於需要實體類支持緩存中的磁盤存儲,所以需要實體類實現可序列化接口

public class user implements Serializable{
    private Integer id;
    private String name;
    private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
    
}

  

第六步,使用@Cacheable把數據存進緩存,下面就是專門把方法返回值存入緩存

@Service
@Transactional     //事務,表示該類下所有的都受事務控制
public class userServiceImpl implements userService {
	@Autowired
    private userMapper usermapper;
	@Override
	@Cacheable(value="users")
	public user selectUserById(int id) {
		user user=this.usermapper.selectUserById(id);
		System.out.println("1111111111111111111111111");
		return user;
	}

}

 說明: @Cacheable可以標記在一個方法上,也可以標記在一個類上,當標記在一個方法上時表示該方法是支持緩存的,當標記在一個類上時則表示該類所有的方法都是支持緩存的。對於一個支持緩存的方法,Spring會在其被調用后將其返回值緩存起來,以保證下次利用同樣的參數來執行該方法時可以直接從緩存中獲取結果,而不需要再次執行該方法。Spring在緩存方法的返回值時是以鍵值對進行緩存的,值就是方法的返回結果。

                 @Cacheable可以指定三個屬性,value、key和condition。

                                  value屬性指定cache的名稱(即選擇ehcache.xml中哪種緩存方式存儲)

                                  key屬性是用來指定Spring緩存方法的返回結果時對應的key的。該屬性支持SpringEL表達式。當我們沒有指定該屬性時,Spring將使用默認策略生成key。我們也直接使用“#參數名”或者“#p參數index”。下面是幾個使用參數作為key的示例

 

   @Cacheable(value="users", key="#id")

   public User find(Integer id) {

      returnnull;

   }

 

   @Cacheable(value="users", key="#p0")

   public User find(Integer id) {

      returnnull;

   }

 

   @Cacheable(value="users", key="#user.id")

   public User find(User user) {

      returnnull;

   }

 

   @Cacheable(value="users", key="#p0.id")

   public User find(User user) {

      returnnull;

   }

   最后,使用@CacheEvict清除緩存;

@CacheEvict(value="users",allEntries=true)
public void saveUsers(Users users) {
this.usersRepository.save(users);
}

  說明:@CacheEvict是用來標注在需要清除緩存元素的方法或類上的。當標記在一個類上時表示其中所有的方法的執行都會觸發緩存的清除操作。@CacheEvict可以指定的屬性有value、key、condition、allEntries和beforeInvocation。

                    其中value、key和condition的語義與@Cacheable對應的屬性類似;allEntries是boolean類型,表示是否需要清除緩存中的所有元素。默認為false,表示不需要。

                   當指定了allEntries為true時,Spring Cache將忽略指定的key。有的時候我們需要Cache一下清除所有的元素,這比一個一個清除元素更有效率。

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM