创建个项目
先看下大概路径
新建个springboot项目
然后是pom
<?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 https://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.3.1.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
然后是application.properties
spring.cache.jcache.config=classpath:ehcache.xml
然后是ehcache的配置文件
<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.pojo.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>
然后是实体类
package com.ramostear.cache.pojo;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
/**
* Created by IntelliJ IDEA.
* User: zhuangzibing
* Date: 2020/7/17
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable {
private Long id;
private String username;
private String email;
}
然后是 service层,注意注解@Cacheable
package com.ramostear.cache.service;
import com.ramostear.cache.pojo.Person;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* Created by IntelliJ IDEA.
* User: zhuangzibing
* Date: 2020/7/17
*/
@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;
}
}
然后是 PersonCacheEventLogger。这个类是缓存事件监听器,用于记录系统操作缓存数据的情况,最快的方法是实现CacheEventListener接口
package com.ramostear.cache.config;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by IntelliJ IDEA.
* User: zhuangzibing
* Date: 2020/7/17
*/
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());
}
}
控制器,这里的ResponseEntity可以定义返回的HttpStatus(状态码)和HttpHeaders(消息头:请求头和响应头)
package com.ramostear.cache.controller;
import com.ramostear.cache.pojo.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;
/**
* Created by IntelliJ IDEA.
* User: zhuangzibing
* Date: 2020/7/17
*/
@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);
}
}
最后是控制器,注意控制器的注解,要启动 ehcache
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);
}
}
以上准备工作都完成后,让我们编译并运行应用程序。项目成功启动后,使用浏览器打开: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,没有任何缓存数据。因此,Ehcache创建了一条缓存数据,可以通过CREATED看一了解到。
我们在ehcache.xml文件中将缓存过期时间设置成了1分钟(<ttl unit="minutes">1</ttl>),因此在一分钟之内我们刷新浏览器,不会看到有新的日志输出,一分钟之后,缓存过期,我们再次刷新浏览器,将看到如下的日志输出:
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
第一条日志提示缓存已经过期,第二条日志提示Ehcache重新创建了一条缓存数据。
以上参考了作者:ramostear。链接:https://www.jianshu.com/p/f4126ee58df1