Springboot集成Ehcache3实现本地缓存

如果只需要在单个应用程序中使用本地缓存,则可以选择Ehcache;它支持内存和磁盘存储,这里不以注解方式演示,通过自己实现缓存管理者灵活控制缓存的读写;

1、引入相关依赖

		<!-- ehcache3集成start -->
		<dependency>
			<groupId>org.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>3.10.8</version>
		</dependency>
		<dependency>
			<groupId>javax.cache</groupId>
			<artifactId>cache-api</artifactId>
		</dependency>
		<!-- ehcache3集成end -->

2、修改yml配置

spring:
  cache:
    type: jcache
    jcache:
      config: classpath:cache/ehcache.xml

3、配置ehcache.xml文件

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.ehcache.org/v3"
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd">
    <!-- 缓存持久化配置: 定义磁盘缓存位置 -->
    <persistence directory="E:/project_home/limit_control/cache/light-element-mybatis"/>
    <!-- 缓存模板: 未填写缓存名时使用的默认缓存,同时也可被继承 -->
    <cache-template name="defaultCache">
        <key-type>java.lang.String</key-type>
        <value-type>java.lang.Object</value-type>
        <resources>
            <heap unit="MB">64</heap>
            <offheap unit="MB">128</offheap>
        </resources>
    </cache-template>
    <!-- 缓存列表: 自定义缓存配置 -->
    <!-- 不过期 -->
    <cache alias="EXPIRE_NONE" uses-template="defaultCache"/>
    <!-- 24小时过期 -->
    <cache alias="EXPIRE_24_HOURS" uses-template="defaultCache">
        <expiry>
            <ttl unit="hours">24</ttl>
        </expiry>
    </cache>
    <!-- 30分钟过期 -->
    <cache alias="EXPIRE_30_MINUTES" uses-template="defaultCache">
        <expiry>
            <ttl unit="minutes">30</ttl>
        </expiry>
    </cache>
</config>

4、编写缓存策略枚举

public enum CacheStrategy {
    EXPIRE_30_MINUTES,
    EXPIRE_24_HOURS,
    EXPIRE_NONE
}

5、编写缓存管理者,来控制缓存的增删改查

import com.alibaba.fastjson.JSON;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * ehcache3缓存管理者
 */
@Configuration
@EnableCaching
public class EhCacheManager {
    private static CacheManager cacheManager;

    public EhCacheManager(CacheManager cacheManager) {
        EhCacheManager.cacheManager = cacheManager;
    }

    /**
     * 获取默认缓存
     *
     * @return
     */
    public static Cache getDefaultCache() {
        return getCache("EXPIRE_24_HOURS");
    }

    /**
     * 获取指定缓存
     *
     * @param cacheName 缓存名称
     * @return
     */
    public static Cache getCache(String cacheName) {
        if (cacheManager == null) {
            return null;
        }
        return cacheManager.getCache(cacheName);
    }

    /**
     * 获取缓存内容(对象)
     *
     * @param cacheName 缓存名称
     * @param key       键
     * @param clazz<T>  class类型
     * @return
     */
    public static <T extends Object> T getObjValue(String cacheName, String key, Class<T> clazz) {
        Object o = getValue(cacheName, key);
        if (o == null) {
            return null;
        }
        T t = (T) JSON.parseObject(JSON.toJSONString(o), clazz);
        return t;
    }

    /**
     * 获取缓存内容(集合)
     *
     * @param cacheName 缓存名称
     * @param key       键
     * @param clazz<T>  class类型
     * @return
     */
    public static <T extends Object> List<T> getListValue(String cacheName, String key, Class<T> clazz) {
        Object o = getValue(cacheName, key);
        if (o == null) {
            return null;
        }
        List<T> ts = JSON.parseArray(JSON.toJSONString(o), clazz);
        return ts;
    }

    /**
     * 获取缓存内容
     *
     * @param cacheName
     * @param key
     * @return
     */
    private static Object getValue(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        if (cache == null && cache.get(key) == null) {
            return null;
        }
        Cache.ValueWrapper valueWrapper = cache.get(key);
        if (valueWrapper == null) {
            return null;
        }
        Object o = valueWrapper.get();
        if (o == null) {
            return null;
        }
        return o;
    }

    /**
     * 新增或修改缓存数据
     *
     * @param cacheName 缓存名称
     * @param key       键
     * @param value     值
     */
    public static void put(String cacheName, String key, Object value) {
        Cache cache = getCache(cacheName);
        if (cache == null) {
            return;
        }
        cache.put(key, value);
    }

    /**
     * 删除缓存数据
     *
     * @param cacheName 缓存名称
     * @param key       键
     */
    public static void del(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        if (cache == null) {
            return;
        }
        cache.evict(key);
    }
}

6、编写controller进行简单测试

import cn.hutool.core.collection.CollectionUtil;
import com.yx.light.element.mybatis.cache.CacheStrategy;
import com.yx.light.element.mybatis.cache.EhCacheManager;
import com.yx.light.element.mybatis.mapper.entity.GroupHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/index")
@Slf4j
public class IndexController {

    @GetMapping(value = "/list")
    public List<GroupHeader> list() {
        List<GroupHeader> listValue = EhCacheManager.getListValue(CacheStrategy.EXPIRE_30_MINUTES.name(), "list", GroupHeader.class);
        if (CollectionUtil.isEmpty(listValue)) {
            log.info("集合缓存不存在或已过期,查询数据库!");
            //模拟查库
            List<GroupHeader> objects = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                GroupHeader groupHeader = new GroupHeader();
                groupHeader.setGroupCode("aaaaa-" + i);
                groupHeader.setGroupName("多个对象" + i);
                objects.add(groupHeader);
            }
            listValue = objects;
            EhCacheManager.put(CacheStrategy.EXPIRE_30_MINUTES.name(), "list", listValue);
            log.info("集合数据加载到缓存!");
        } else {
            log.info("从集合缓存中直接获取数据!");
        }
        return listValue;
    }

    @GetMapping(value = "/one")
    public GroupHeader one() {
        GroupHeader objValue = EhCacheManager.getObjValue(CacheStrategy.EXPIRE_30_MINUTES.name(), "obj", GroupHeader.class);
        if (objValue == null) {
            log.info("对象缓存不存在或已过期,查询数据库!");
            //模拟查库
            GroupHeader groupHeader = new GroupHeader();
            groupHeader.setGroupCode("aaaaa");
            groupHeader.setGroupName("单个对象");
            objValue = groupHeader;
            EhCacheManager.put(CacheStrategy.EXPIRE_30_MINUTES.name(), "obj", groupHeader);
            log.info("对象数据加载到缓存!");
        } else {
            log.info("从对象缓存中直接获取数据!");
        }
        return objValue;
    }

    @GetMapping(value = "/del")
    public void del() {
        log.info("清理对象缓存!");
        EhCacheManager.del(CacheStrategy.EXPIRE_30_MINUTES.name(), "obj");
    }

}

7、分别调用接口查看日志打印

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答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应用中,并且实现了基于注解的缓存管理。需要注意的是,在添加缓存配置信息时,根据实际需求可自行更改缓存过期时间、缓存数量等相关参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值