Ehcache 与 SpringBoot 整合

本文介绍了如何在SpringBoot项目中整合Ehcache进行缓存管理,包括Maven依赖配置、ehcache.xml的配置、Spring Boot启动类注解、接口实现及单元测试。通过实例演示了数据的存取和删除操作,适合对分布式缓存感兴趣的开发者。
摘要由CSDN通过智能技术生成

Ehcache 与 SpringBoot 整合

1、maven依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.72</version>
</dependency>

2、ehcache.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">
    <diskStore path="java.io.tmpdir"/>
    <!--
    name: 缓存名称
    overflowToDisk: 如果内存中数据超过内存限制,是否要缓存到磁盘上
    maxElementsInMemory: 内存中缓存数量的上限
    maxElementsOnDisk:   磁盘上缓存数量的上限
    eternal: 代表对象是否永不过期
    timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效
    timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间
    diskPersistent: 是否在磁盘上持久化,指重启jvm后,数据是否有效,默认为false
    diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔,标识对象状态的线程多长时间运行一次
    memoryStoreEvictionPolicy: 存中数据超过内存限制,向磁盘缓存时的策略,默认值LRU
    -->
    <!-- 默认的必须添加 -->
    <defaultCache
            overflowToDisk="true"
            maxElementsInMemory="10000"
            maxElementsOnDisk="10000000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>

    <cache name="USER"
           overflowToDisk="true"
           maxElementsInMemory="10000"
           maxElementsOnDisk="10000000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           diskPersistent="false"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
    </cache>
</ehcache>

3、application.properties

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

4、SpringBoot启动类中添加注解

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@EnableCaching
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CookieDemoApplication.class, args);
    }
}

5、ICacheService.java

package com.demo.service;

public interface ICacheService {

    void set(String cacheName, String key, Object value);

    <T> T get(String cacheName, String key, Class<T> cls);

    void del(String cacheName, String key);

}

6、EhcacheServiceImpl.java

package com.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.demo.service.ICacheService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

@Service
public class EhcacheServiceImpl implements ICacheService {

    @Autowired
    private CacheManager cacheManager;

    @Override
    public void set(String cacheName, String key, Object value) {
        this.cacheManager.getCache(cacheName).put(key, JSONObject.toJSONString(value));
    }

    @Override
    public <T> T get(String cacheName, String key, Class<T> cls) {
        String str = this.cacheManager.getCache(cacheName).get(key, String.class);
        if (StringUtils.isBlank(str)) {
            return null;
        }

        return JSONObject.parseObject(str, cls);
    }

    @Override
    public void del(String cacheName, String key) {
        this.cacheManager.getCache(cacheName).evictIfPresent(key);
    }
}

7、User.java

package com.demo.model;

public class User {

    private String userId;

    private String userName;

    private String password;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId='" + userId + '\'' +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

8、单元测试

package com.demo.utils;

import com.demo.model.User;
import com.demo.service.impl.EhcacheServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class CacheUtilsTest {

    private static final String CACHE_NAME = "USER";

    @Autowired
    private EhcacheServiceImpl cacheService;

    @Test
    public void test() {
        // 设置
        this.cacheService.set(CACHE_NAME, "lbb", new User() {{
            setUserId("1");
            setUserName("lbb");
            setPassword("123456");
        }});

        // 获取
        User user = this.cacheService.get(CACHE_NAME, "lbb", User.class);
        System.out.println(user);

        // 删除
        this.cacheService.del(CACHE_NAME, "lbb");

        // 检测是否还存在
        user = this.cacheService.get(CACHE_NAME, "lbb", User.class);
        System.out.println(user);
    }
}

9、结果输出

User{userId='1', userName='lbb', password='123456'}
null
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值