SpringBoot中怎么集成Ehcache缓存

本篇文章为大家展示了Spring Boot中怎么集成Ehcache缓存,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

曲周网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。创新互联公司于2013年开始到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

1. 创建一个Spring Boot工程

你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子:



 4.0.0
 
  org.springframework.boot
  spring-boot-starter-parent
  2.1.3.RELEASE
   
 
 com.ramostear
 cache
 0.0.1-SNAPSHOT
 cache
 Demo project for Spring Boot

 
  1.8
 

 
  
   org.springframework.boot
   spring-boot-starter-cache
  
  
   org.springframework.boot
   spring-boot-starter-web
  
  
   org.ehcache
   ehcache
  
  
   javax.cache
   cache-api
  
  
   org.springframework.boot
   spring-boot-starter-test
   test
  
  
   org.projectlombok
   lombok
  
 

 
  
   
    org.springframework.boot
    spring-boot-maven-plugin
   
  
 

依赖说明:

  • spring-boot-starter-cache为Spring Boot应用程序提供缓存支持

  • ehcache提供了Ehcache的缓存实现

  • cache-api 提供了基于JSR-107的缓存规范

2. 配置Ehcache缓存

现在,需要告诉Spring Boot去哪里找缓存配置文件,这需要在Spring Boot配置文件中进行设置:

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

然后使用@EnableCaching注解开启Spring Boot应用程序缓存功能,你可以在应用主类中进行操作:

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);
 }
}

接下来,需要创建一个 ehcache 的配置文件,该文件放置在类路径下,如resources目录下:


  
    
  

  
    java.lang.Long
    com.ramostear.cache.entity.Person
    
      1
    
    
      
        com.ramostear.cache.config.PersonCacheEventLogger
        ASYNCHRONOUS
        UNORDERED
        CREATED
        UPDATED
        EXPIRED
        REMOVED
        EVICTED
      
    
    
        2000
        100
    
  

最后,还需要定义个缓存事件监听器,用于记录系统操作缓存数据的情况,最快的方法是实现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{

  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注解

要让Spring Boot能够缓存我们的数据,还需要使用@Cacheable注解对业务方法进行注释,告诉Spring Boot该方法中产生的数据需要加入到缓存中:

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的缓存功能。接下来,我们将测试一下缓存的实际情况。

4. 缓存测试

为了测试我们的应用程序,创建一个简单的Restful端点,它将调用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(@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;
}

以上准备工作都完成后,让我们编译并运行应用程序。项目成功启动后,使用浏览器打开:http://localhost:8080/persons/1 ,你将在浏览器页面中看到如下的信息:

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

此时在观察控制台输出的日志信息:

1. 2019-04-07 01:08:01.001 INFO 6704 --- [nio-8080-exec-1] 
o.s.web.servlet.DispatcherServlet    : Completed 
initialization in 5 ms
2. 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分钟(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 null
2. 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重新创建了一条缓存数据。

上述内容就是Spring Boot中怎么集成Ehcache缓存,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。


文章题目:SpringBoot中怎么集成Ehcache缓存
网站地址:http://lszwz.com/article/gejgcc.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款