如何在ehcache中緩存springboot

如何在ehcache中緩存springboot?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供醴陵網(wǎng)站建設(shè)、醴陵做網(wǎng)站、醴陵網(wǎng)站設(shè)計(jì)、醴陵網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、醴陵企業(yè)網(wǎng)站模板建站服務(wù),十多年醴陵做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計(jì)目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

1. 創(chuàng)建一個Spring Boot工程并添加Maven依賴

你所創(chuàng)建的Spring Boot應(yīng)用程序的maven依賴文件至少應(yīng)該是下面的樣子:

<?xml version="1.0" encoding="UTF-8"?>
<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>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.3.RELEASE</version>
 <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.ramostear</groupId>
 <artifactId>cache</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>cache</name>
 <description>Demo project for Spring Boot</description>

 <properties>
 <java.version>1.8</java.version>
 </properties>

 <dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
  <groupId>org.ehcache</groupId>
  <artifactId>ehcache</artifactId>
 </dependency>
 <dependency>
  <groupId>javax.cache</groupId>
  <artifactId>cache-api</artifactId>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
 </dependency>
 <dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
 </dependency>
 </dependencies>

 <build>
 <plugins>
  <plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  </plugin>
 </plugins>
 </build>

</project>

依賴說明:

  • spring-boot-starter-cache為Spring Boot應(yīng)用程序提供緩存支持

  • ehcache提供了Ehcache的緩存實(shí)現(xiàn)

  • cache-api 提供了基于JSR-107的緩存規(guī)范

2. 配置Ehcache緩存

現(xiàn)在,需要告訴Spring Boot去哪里找緩存配置文件,這需要在Spring Boot配置文件中進(jìn)行設(shè)置:

spring.cache.jcache.config=classpath:ehcache.xml

然后使用@EnableCaching注解開啟Spring Boot應(yīng)用程序緩存功能,你可以在應(yīng)用主類中進(jìn)行操作:

package com.ramostear.cache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class CacheApplication {

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

接下來,需要創(chuàng)建一個ehcache的配置文件,該文件放置在類路徑下,如resources目錄下:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.ehcache.org/v3"
    xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
    xsi:schemaLocation="
      http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
      http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
  <service>
    <jsr107:defaults enable-statistics="true"/>
  </service>

  <cache alias="person">
    <key-type>java.lang.Long</key-type>
    <value-type>com.ramostear.cache.entity.Person</value-type>
    <expiry>
      <ttl unit="minutes">1</ttl>
    </expiry>
    <listeners>
      <listener>
        <class>com.ramostear.cache.config.PersonCacheEventLogger</class>
        <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
        <event-ordering-mode>UNORDERED</event-ordering-mode>
        <events-to-fire-on>CREATED</events-to-fire-on>
        <events-to-fire-on>UPDATED</events-to-fire-on>
        <events-to-fire-on>EXPIRED</events-to-fire-on>
        <events-to-fire-on>REMOVED</events-to-fire-on>
        <events-to-fire-on>EVICTED</events-to-fire-on>
      </listener>
    </listeners>
    <resources>
        <heap unit="entries">2000</heap>
        <offheap unit="MB">100</offheap>
    </resources>
  </cache>
</config>

最后,還需要定義個緩存事件監(jiān)聽器,用于記錄系統(tǒng)操作緩存數(shù)據(jù)的情況,最快的方法是實(shí)現(xiàn)CacheEventListener接口:

package com.ramostear.cache.config;

import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ramostear
 * @create-time 2019/4/7 0007-0:48
 * @modify by :
 * @since:
 */
public class PersonCacheEventLogger implements CacheEventListener<Object,Object>{

  private static final Logger logger = LoggerFactory.getLogger(PersonCacheEventLogger.class);

  @Override
  public void onEvent(CacheEvent cacheEvent) {
    logger.info("person caching event {} {} {} {}",
        cacheEvent.getType(),
        cacheEvent.getKey(),
        cacheEvent.getOldValue(),
        cacheEvent.getNewValue());
  }
}

3. 使用@Cacheable注解對方法進(jìn)行注釋

要讓Spring Boot能夠緩存我們的數(shù)據(jù),還需要使用@Cacheable注解對業(yè)務(wù)方法進(jìn)行注釋,告訴Spring Boot該方法中產(chǎn)生的數(shù)據(jù)需要加入到緩存中:

package com.ramostear.cache.service;

import com.ramostear.cache.entity.Person;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author ramostear
 * @create-time 2019/4/7 0007-0:51
 * @modify by :
 * @since:
 */
@Service(value = "personService")
public class PersonService {

  @Cacheable(cacheNames = "person",key = "#id")
  public Person getPerson(Long id){
    Person person = new Person(id,"ramostear","ramostear@163.com");
    return person;
  }
}

通過以上三個步驟,我們就完成了Spring Boot的緩存功能。接下來,我們將測試一下緩存的實(shí)際情況。

4. 緩存測試

為了測試我們的應(yīng)用程序,創(chuàng)建一個簡單的Restful端點(diǎn),它將調(diào)用PersonService返回一個Person對象:

package com.ramostear.cache.controller;

import com.ramostear.cache.entity.Person;
import com.ramostear.cache.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author ramostear
 * @create-time 2019/4/7 0007-0:54
 * @modify by :
 * @since:
 */
@RestController
@RequestMapping("/persons")
public class PersonController {

  @Autowired
  private PersonService personService;

  @GetMapping("/{id}")
  public ResponseEntity<Person> person(@PathVariable(value = "id") Long id){
    return new ResponseEntity<>(personService.getPerson(id), HttpStatus.OK);
  }
}

Person是一個簡單的POJO類:

package com.ramostear.cache.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author ramostear
 * @create-time 2019/4/7 0007-0:45
 * @modify by :
 * @since:
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable{

  private Long id;

  private String username;

  private String email;
}

以上準(zhǔn)備工作都完成后,讓我們編譯并運(yùn)行應(yīng)用程序。項(xiàng)目成功啟動后,使用瀏覽器打開: http://localhost:8080/persons/1 ,你將在瀏覽器頁面中看到如下的信息:

{"id":1,"username":"ramostear","email":"ramostear@163.com"}

此時在觀察控制臺輸出的日志信息:

2019-04-07 01:08:01.001  INFO 6704 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-04-07 01:08:01.054  INFO 6704 --- [e [_default_]-0] c.r.cache.config.PersonCacheEventLogger  : person caching event CREATED 1 null com.ramostear.cache.entity.Person@ba8a729

由于我們是第一次請求API,沒有任何緩存數(shù)據(jù)。因此,Ehcache創(chuàng)建了一條緩存數(shù)據(jù),可以通過 CREATED 看一了解到。

我們在ehcache.xml文件中將緩存過期時間設(shè)置成了1分鐘(1),因此在一分鐘之內(nèi)我們刷新瀏覽器,不會看到有新的日志輸出,一分鐘之后,緩存過期,我們再次刷新瀏覽器,將看到如下的日志輸出:

2019-04-07 01:09:28.612  INFO 6704 --- [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger  : person caching event EXPIRED 1 com.ramostear.cache.entity.Person@a9f3c57 null
2019-04-07 01:09:28.612  INFO 6704 --- [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger  : person caching event CREATED 1 null com.ramostear.cache.entity.Person@416900ce

關(guān)于如何在ehcache中緩存springboot問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

網(wǎng)頁名稱:如何在ehcache中緩存springboot
網(wǎng)站地址:http://bm7419.com/article26/pcegcg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃網(wǎng)站設(shè)計(jì)、品牌網(wǎng)站制作網(wǎng)站內(nèi)鏈、網(wǎng)站排名、全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護(hù)公司