spring注解集成ehcache

1、applicationContext.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache-3.2.xsd        
    default-lazy-init="true">

    <!-- 支持缓存注解 -->
    <cache:annotation-driven cache-manager="cacheManager" />
    <!-- 默认是cacheManager -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="cacheManagerFactory" />
    </bean>
    <!--  缓存  属性-->
    <bean id="cacheManagerFactory"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
    </bean>
</beans>

2、ehcache.xml 配置
<ehcache>
    <diskStore path="java.io.tmpdir" />
    <defaultCache maxElementsInMemory="0" eternal="false"
        timeToIdleSeconds="0" timeToLiveSeconds="0" overflowToDisk="false" />
    
    <cache name="okdiEhcache" maxElementsInMemory="500"
        eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="0"
        overflowToDisk="false" memoryStoreEvictionPolicy="LRU" />
</ehcache>

<!--
<diskStore>==========当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)
<diskStore path="">==用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index
name=================缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)
maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大
maxElementsInMemory==内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况
                     1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中
                     2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素
eternal==============缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds
timeToIdleSeconds====缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性
                     即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
timeToLiveSeconds====缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大
                     即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除
overflowToDisk=======内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中)
                     会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data
diskPersistent=======是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件
                     这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存
                     要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法
diskExpiryThreadIntervalSeconds==磁盘缓存的清理线程运行间隔,默认是120秒
diskSpoolBufferSizeMB============设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB
memoryStoreEvictionPolicy========内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存
                                 共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)
-->

3、缓存处理

package com.jadyer.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class UserService {
  private Map<String, String> usersData = new ConcurrentHashMap<String, String>();
 
 
 
  //将查询到的数据缓存到myCache中,并使用方法名称加上参数中的userNo作为缓存的key
  //通常更新操作只需刷新缓存中的某个值,所以为了准确的清除特定的缓存,故定义了这个唯一的key,从而不会影响其它缓存值
  @Cacheable(value="myCache", key="'get'+#userNo")
  public String get(String userNo){
    System.out.println("数据库中查到此用户号[" + userNo + "]对应的用户名为[" + usersData.get(userNo) + "]");
    return usersData.get(userNo);
  }
 
  @CacheEvict(value="myCache", key="'get'+#userNo")
  public void update(String userNo){
    System.out.println("移除缓存中此用户号[" + userNo + "]对应的用户名[" + usersData.get(userNo) + "]的缓存");
  }
 
  //allEntries为true表示清除value中的全部缓存,默认为false
  @CacheEvict(value="myCache", allEntries=true)
  public void removeAll(){
    System.out.println("移除缓存中的所有数据");
  }
}

注意:Cacheable 默认的key是方法名字+参数名,也可以自定义key

4、需要的jar包

slf4j-api-1.6.6.jar
slf4j-log4j12-1.6.6.jar
log4j-1.2.17.jar
ehcache-2.7.2.jar
还有一些spring需要的jar包具体就不写了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot集成Ehcache可以通过以下步骤实现: 1. 添加Ehcache依赖 在pom.xml文件中添加Ehcache依赖: ``` <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.8.1</version> </dependency> ``` 2. 配置Ehcache 在application.properties文件中添加Ehcache配置: ``` # Ehcache配置 spring.cache.type=ehcache spring.cache.ehcache.config=classpath:ehcache.xml ``` 其中,ehcache.xml是Ehcache的配置文件,可以在该文件中配置缓存策略、缓存大小等参数。 3. 使用Ehcache缓存数据 在需要缓存数据的方法上添加@Cacheable注解,指定缓存名称和缓存key: ``` @Cacheable(value = "userCache", key = "#id") public User getUserById(Long id) { // 从数据库中获取用户信息 User user = userRepository.findById(id).orElse(null); return user; } ``` 其中,value属性指定缓存名称,key属性指定缓存key,可以使用SpEL表达式指定key的值。 4. 清除缓存数据 在需要清除缓存数据的方法上添加@CacheEvict注解,指定缓存名称和缓存key: ``` @CacheEvict(value = "userCache", key = "#id") public void deleteUserById(Long id) { // 从数据库中删除用户信息 userRepository.deleteById(id); } ``` 其中,value属性指定缓存名称,key属性指定缓存key,可以使用SpEL表达式指定key的值。 以上就是Spring Boot集成Ehcache的基本步骤,通过使用Ehcache可以提高应用程序的性能和响应速度。 ### 回答2: Spring Boot是一个非常流行的轻量级框架,它简化了Java应用程序的开发。另一方面,Ehcache是一个开源的Java缓存框架,可在我们的应用程序中使用,以提高性能和可伸缩性。当将这两者结合在一起时,我们可以实现一个高性能的应用程序。本文将向您介绍如何在Spring Boot中集成Ehcache。 步骤1:添加Ehcache依赖项 首先,我们需要向项目中添加以下Ehcache依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 步骤2:在应用程序上启用缓存 在application.properties文件中,我们需要添加以下配置以启用缓存: ``` spring.cache.type=ehcache ``` 步骤3:定义缓存 在我们的代码中,我们需要定义缓存。可以使用@Cacheable注释将一个方法声明为可缓存的,也可以使用@CacheEvict注释将一个方法标记为删除缓存的。 例如: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "users", key = "#username") public User getUserByUsername(String username) { return userRepository.findByUsername(username); } @CacheEvict(value = "users", key = "#username") public void deleteUserByUsername(String username) { userRepository.deleteByUsername(username); } } ``` 步骤4:使用缓存 在我们的代码中,我们可以像平常一样使用userService,Spring Boot将自动为我们处理缓存。 例如: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users/{username}") public ResponseEntity getUserByUsername(@PathVariable String username) { User user = userService.getUserByUsername(username); return ResponseEntity.ok(user); } @DeleteMapping("/users/{username}") public ResponseEntity deleteUserByUsername(@PathVariable String username) { userService.deleteUserByUsername(username); return ResponseEntity.noContent().build(); } } ``` 总结 在本文中,我们介绍了如何在Spring Boot中集成Ehcache。我们了解了如何添加Ehcache依赖项,启用缓存,定义缓存和使用缓存。现在,您应该能够使用Ehcache轻松地优化自己的应用程序。 ### 回答3: Spring Boot是现今非常流行的Java web开发框架,其本质就是一个基于Spring框架的快速开发工具。随着Spring Boot的发展,其内部集成了很多流行的组件,其中也包括了ehcacheehcache是一个广泛使用的Java开源缓存框架,可以提高应用程序的性能和扩展性。 Spring Boot集成ehcache非常容易,在此我们简单介绍一下集成步骤: 1. 在pom.xml文件中添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency> ``` 2. 在配置文件application.properties中添加ehcache的相关配置信息: ```properties # 缓存管理器 Ehcache 必须制定一个唯一的名称 spring.cache.cache-names=myCache # ehcache 配置信息 spring.cache.ehcache.config=classpath:ehcache.xml ``` 3. 在配置文件classpath下添加ehcache.xml文件,配置缓存策略。例如如下所示: ```xml <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="0" diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" statistics="true"> <persistence strategy="localTempSwap" /> </defaultCache> <cache name="myCache" maxEntriesLocalHeap="1000" maxEntriesLocalDisk="0" eternal="true" timeToIdleSeconds="0" timeToLiveSeconds="0" memoryStoreEvictionPolicy="LRU"> <persistence strategy="none" /> </cache> </ehcache> ``` 4. 创建自定义缓存注解和实现类: ```java @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Cacheable(cacheNames = "myCache") public @interface MyCache { } @Component public class MyCacheManager implements CachingConfigurerSupport { @Bean public CacheManager cacheManager() { return new EhCacheCacheManager(ehCacheCacheManager().getObject()); } @Bean public EhCacheManagerFactoryBean ehCacheCacheManager() { EhCacheManagerFactoryBean cmfb = new EhCacheManagerFactoryBean(); cmfb.setConfigLocation(new ClassPathResource("ehcache.xml")); cmfb.setShared(true); return cmfb; } } ``` 5. 修改对应的Controller和Service方法,并添加自定义缓存注解: ```java @Service public class UserService { @MyCache public String getUser(int id) { return "user from db"; } } @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{id}") public String getUser(@PathVariable("id") int id) { return userService.getUser(id); } } ``` 6. 启动应用,测试是否生效。 通过以上6个步骤,我们就成功地将ehcache缓存组件集成到了Spring Boot应用中,并且实现了基于注解缓存管理。需要注意的是,在添加缓存配置信息时,根据实际需求可自行更改缓存过期时间、缓存数量等相关参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值