<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
依赖说明:
package com.linyf.demo.ehcache;
import lombok.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class Person implements Serializable {
private Long id;
private String username;
private String email;
}
说明:@Data和@AllArgsConstructor为lombok中的注解,不了解的推荐阅读:效率工具Lombok
用于记录系统操作缓存数据的情况,实现CacheEventListener接口:
package com.linyf.demo.ehcache;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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());
}
}
在resources资源根目录下创建ehcache.xml,内容如下:
<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.Longkey-type>
<value-type>com.linyf.demo.ehcache.Personvalue-type>
<expiry>
<ttl unit="minutes">1ttl>
expiry>
<listeners>
<listener>
<class>com.linyf.demo.ehcache.PersonCacheEventLoggerclass>
<event-firing-mode>ASYNCHRONOUSevent-firing-mode>
<event-ordering-mode>UNORDEREDevent-ordering-mode>
<events-to-fire-on>CREATEDevents-to-fire-on>
<events-to-fire-on>UPDATEDevents-to-fire-on>
<events-to-fire-on>EXPIREDevents-to-fire-on>
<events-to-fire-on>REMOVEDevents-to-fire-on>
<events-to-fire-on>EVICTEDevents-to-fire-on>
listener>
listeners>
<resources>
<heap unit="entries">2000heap>
<offheap unit="MB">100offheap>
resources>
cache>
config>
现在需要告诉Spring Boot去哪里找缓存配置文件,在application.yml中进行设置:
spring:
cache:
jcache:
config: classpath:ehcache.xml
使用@EnableCaching注解开启Spring Boot应用程序缓存功能,可以添加到启动类中:
package com.linyf.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
package com.linyf.demo.ehcache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service(value = "personService")
public class PersonService {
@Cacheable(cacheNames = "person", key = "#id")
public Person getPerson(Long id){
Person person = new Person(id,"linyf","[email protected]");
return person;
}
}
创建controller:
package com.linyf.demo.ehcache;
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;
@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);
}
}
然后通过浏览器访问:
看控制台打印信息,打印了一条创建缓存数据的日志:
因为是第一次访问,缓存中没有,所以会创建一个缓存数据存到缓存中,有效时间是一分钟。
一分钟内再次访问,就会读取缓存,所以不会打印任何日志,隔一分钟后再次访问,打印了两条日志,一条过期日志,一条创建日志: