精通Spring Boot——第二十四篇:Spring Boot 整合ehcache緩存

1. 該說的話

每個人都應當學會獨立地去思考、去尋找答案,而不是一味地伸手向他人索取所謂的標準答案。 首先,別成爲“拿來主義”者,其次遠離"拿來主義"的人。

2. ehcache

2.1 主要特性

  1. 快速,簡單.
  2. 多種緩存策略
  3. 緩存數據有兩級:內存和磁盤,因此無需擔心容量問題
  4. 緩存數據會在虛擬機重啓的過程中寫入磁盤
  5. 可以通過RMI、可插入API等方式進行分佈式緩存
  6. 具有緩存和緩存管理器的偵聽接口
  7. 支持多緩存管理器實例,以及一個實例的多個緩存區域
  8. 提供Hibernate的緩存實現

2.2 和redis相比

  • ehcache直接在jvm虛擬機中緩存,速度快,效率高;但是緩存共享麻煩,集羣分佈式應用不方便。
  • redis是通過socket訪問到緩存服務,效率比ecache低,比數據庫要快很多.

2.3 在應用程序中的位置

3. spring boot 整合

1.搭建spring boot 項目 2. pom.xml文件中添加依賴

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache</artifactId>
</dependency>
  1. 添加ehcache.xml配置文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

<!--
        磁盤存儲:將緩存中暫時不使用的對象,轉移到硬盤,類似於Windows系統的虛擬內存
        path:指定在硬盤上存儲對象的路徑
        path可以配置的目錄有:
            user.home(用戶的家目錄)
            user.dir(用戶當前的工作目錄)
            java.io.tmpdir(默認的臨時目錄)
            ehcache.disk.store.dir(ehcache的配置目錄)
            絕對路徑(如:d:\\ehcache)
        查看路徑方法:String tmpDir = System.getProperty("java.io.tmpdir");
     -->
    <diskStore path="java.io.tmpdir" />

    <!--
        defaultCache:默認的緩存配置信息,如果不加特殊說明,則所有對象按照此配置項處理
        maxElementsInMemory:設置了緩存的上限,最多存儲多少個記錄對象
        eternal:代表對象是否永不過期 (指定true則下面兩項配置需爲0無限期)
        timeToIdleSeconds:最大的發呆時間 /秒
        timeToLiveSeconds:最大的存活時間 /秒
        overflowToDisk:是否允許對象被寫入到磁盤
        說明:下列配置自緩存建立起600秒(10分鐘)有效 。
        在有效的600秒(10分鐘)內,如果連續120秒(2分鐘)未訪問緩存,則緩存失效。
        就算有訪問,也只會存活600秒。
     -->
    <defaultCache maxElementsInMemory="10000" eternal="false"
                  timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="true" />

    <!--有效時間: 7200秒 = 2小時 ,連續180秒 = 3分鐘未訪問緩存,則失效-->
    <cache name="userCache" maxElementsInMemory="10000" eternal="false"
           timeToIdleSeconds="1800" timeToLiveSeconds="7200" overflowToDisk="true" />

</ehcache>
  1. 啓用緩存 在啓動類添加 @EnableCaching 註解。 5.應用 如下代碼所示,你可以在函數上使用@Cacheable,@CachePut,@CacheEvict,來新增、更新、刪除緩存。 注意,當這個類中所有的緩存都處於同一緩存區時,你可以在類名上方使用@CacheConfig(cacheNames =userCache )來配置,這樣在函數註解上就不需要再寫 value = userCache。(cacheNames 的值在ehcache.xml文件中配置。)
@Service
public class UserServiceImpl implements IUserService {


    @Resource
    private UserRepository userRepository;

    @Override
    @Cacheable(value = "userCache", key = "#user.id")
    public boolean addUser(UserEntity user) {
        return userRepository.saveAndFlush(user).getId() != null;
    }

    @Override
    @CachePut(value = "userCache", key = "#user.id")
    public boolean updateUser(UserEntity user) {
        return userRepository.saveAndFlush(user).getId() != null;
    }

    @Override
    @CacheEvict(value = "userCache", key = "#id")
    public boolean deleteUser(Long id) {
        return false;
    }

    @Override
    @Cacheable(value = "userCache", key = "#id")
    public UserEntity selectUser(Long id) {
        return null;
    }
}

當你想要刪除某一緩存區所有緩存時,可以使用 @CacheEvict(value = "userCache", allEntries = true), 刪除userCache中所有的緩存。

4. “毒雞湯”,和我一起幹了吧!

每個人都“畫地爲牢”,把志同道合者劃入圈內,把異己者排除在外。選好你的“地”,劃好你的“圈”。“親賢臣,遠小人,此先漢所以興隆也;親小人,遠賢臣,此後漢所以傾頹也。” 把自己經營好,就相當於把自己的圈子經營好,和志同道合者,一同去征服星辰大海!

示例代碼可在我的 github.com 中找到。 個人博客地址:劉一手的博客。 歡迎關注公衆號:鍋外的大佬,關注我,不迷路。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章