做者:谭朝红html
www.ramostear.com/articles/spring_boot_ehcache.htmljava
1. 建立一个Spring Boot工程
你所建立的Spring Boot应用程序的maven依赖文件至少应该是下面的样子:web
<?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
apache
编程
json
后端
api
依赖说明:
spring-boot-starter-cache为Spring Boot应用程序提供缓存支持
ehcache提供了Ehcache的缓存实现
cache-api 提供了基于JSR-107的缓存规范
2. 配置Ehcache缓存
spring.cache.jcache.config=classpath:ehcache.xml
package com.ramostear.cache;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication@EnableCachingpublic class CacheApplication { public static void main(String[] args) { SpringApplication.run(CacheApplication.class, args); }}
<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>
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注解
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; }}
4. 缓存测试
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); }}
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@NoArgsConstructorpublic class Person implements Serializable{ private Long id; private String username; private String email;}
{"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 ms2019-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分钟(
1 ),所以在一分钟以内咱们刷新浏览器,不会看到有新的日志输出,一分钟以后,缓存过时,咱们再次刷新浏览器,将看到以下的日志输出:
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 null2019-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从新建立了一条缓存数据。
结束语
- END -
关注微信公众号,在后台回复关键字:Java,能够获取一份整理的 Java 最新技术干货。
最近干货分享
看完本文有收获?请转发分享给更多人
本文分享自微信公众号 - Java后端编程(java_hdbc)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。