SpringBoot中使用ehcache

本文详细介绍了如何在SpringBoot应用中集成并使用EhCache进行缓存操作,包括引入依赖、配置ehcache.xml、配置application.yml、启用缓存功能,以及注解和编程方式的缓存使用方法。特别指出在注解方式失效时,如何通过EhCacheUtil进行缓存处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入依赖

<!--ehcache依赖-->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2.创建EhCache的配置文件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"
         updateCheck="false">

    <!--
        磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
        path:指定在硬盘上存储对象的路径
        path可以配置的目录有:
        user.home(用户的家目录)
        user.dir(用户当前的工作目录)
        java.io.tmpdir(默认的临时目录)
        ehcache.disk.store.dir(ehcache的配置目录)
        绝对路径(如:d:\\ehcache)
        查看路径方法:String tmpDir = System.getProperty("java.io.tmpdir");
     -->
    <diskStore path="java.io.tmpdir" />

    <!--
        defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
        maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象
        eternal:代表对象是否永不过期 (指定true则下面两项配置需为0无限期)
        timeToIdleSeconds:最大的发呆时间 /秒
        timeToLiveSeconds:最大的存活时间 /秒
        overflowToDisk:是否允许对象被写入到磁盘
        说明:下列配置自缓存建立起600秒(10分钟)有效 。
        在有效的600秒(10分钟)内,如果连续120秒(2分钟)未访问缓存,则缓存失效。
        就算有访问,也只会存活600秒。
     -->
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
                  timeToLiveSeconds="600" overflowToDisk="true" />

    <cache name="users" maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120"
           timeToLiveSeconds="600" overflowToDisk="true" />

</ehcache>

3.application.yml中,指明缓存类型并声明Ehcache配置文件的位置

	server:
	  port: 8899
	
	spring:
	  profiles:
	    active: dev
	  cache:
	    type: ehcache
	    ehcache:
	      config: classpath:/ehcache.xml

4.SpringBoot启动类,@EnableCaching开启Spring Cache缓存功能

@EnableCaching
@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
    
    @Bean  
	public EhCacheCacheManager ehCacheCacheManager(){
	   EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); 
	   cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("ehcache.xml"));
	   cacheManagerFactoryBean.setShared(true); 
	   return new EhCacheCacheManager(cacheManagerFactoryBean.getObject());
	}
}

5.使用缓存

5.1 使用注解的方式使用缓存
@Service
@Transactional     //事务,表示该类下所有的都受事务控制
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper usermapper;
    
    @Override
    @Cacheable(value="users",key="#id")
    public User selectUserById(int id) {
        User user=this.usermapper.selectUserById(id);
        return user;
    }
 
}
5.2 通过编程方式使用缓存(注解无效的情况下)

由于@Cacheable基于SpringAOP的动态代理机制,程序执行时会在代理的方法前做缓存处理,但是如果一个类(比如一个加了@Service注解的)内部方法A调用内部的@Cacheable方法B,则会直接调用方法不会进行相应的处理
解决办法:1.把A、B两个方法放进不同的Service中 2.不采用注解的方式,直接采用编程方式


@Service
@Transactional    
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper usermapper;
    
    @Override
    @Cacheable(value="users",key="#id")
    public User selectUserById(int id) {
        User user=selectUserById2(id);
        return user;
    }

	public User selectUserById2(int id) {
        User user=this.usermapper.selectUserById(id);
        return user;
    }
}

通过EhCacheUtil使用缓存

@Service
@Transactional    
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper usermapper;
    
    @Override
    public User selectUserById(int id) {
        User user=selectUserById2(id);
        return user;
    }

	public User selectUserById2(int id) {
	    if(EhCacheUtil.get("users",id) != null){
	    	User user = (User)EhCacheUtil.get("users",id);
	    	return user;
		}
        User user=this.usermapper.selectUserById(id);
        EhCacheUtil.put("users",id,user);
        return user;
    }
}
EhCacheUtil
/**
 * @ClassName:EhCacheUtil
 * @Description: <p> Ehcache工具类   </p>
*/
public class EhCacheUtil {

    /**
     * @Description: 获取缓存
     * @param cacheName 缓存名字
     * @return Cache
     */
    private static Cache getCache(String cacheName) {
        CacheManager cacheManager = CacheManager.getInstance();
        if (null == cacheManager) {
            return null;
        }
        Cache cache = cacheManager.getCache(cacheName);
        if (null == cache) {
            return null;
        }
        return cache;
    }

    /**
     * @Description:    新增缓存记录
     * @param cacheName 缓存名字
     * @param key       缓存key
     */
    public static void put(String cacheName, String key, Object value) {
        Cache cache = getCache(cacheName);
        if (null != cache) {
            Element element = new Element(key, value);
            cache.put(element);
        }
    }

    /**
     * @Description:    删除缓存记录
     * @param cacheName 缓存名字
     * @param key       缓存key
     * @return boolean  是否成功删除
     */
    public static boolean remove(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        if (null == cache) {
            return false;
        }
        return cache.remove(key);
    }

    /**
     * @Description: 删除全部缓存记录
     * @param cacheName 缓存名字
     */
    public static void removeAll(String cacheName) {
        Cache cache = getCache(cacheName);
        if (null != cache) {
            //logOnRemoveAllIfPinnedCache();
            cache.removeAll();
        }
    }

    /**
     * @Description: 获取缓存记录
     * @param cacheName  缓存名字
     * @param key        缓存key
     * @return Object    缓存记录数据Object
     */
    public static Object get(String cacheName, String key) {
        Cache cache = getCache(cacheName);
        if (null == cache) {
            return null;
        }
        Element cacheElement = cache.get(key);
        if (null == cacheElement) {
            return null;
        }
        return cacheElement.getObjectValue();
    }


}
首先,需要在 `pom.xml` 文件中添加 `ehcache` 依赖: ```xml <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.6</version> </dependency> ``` 然后,在 Spring Boot 应用程序的配置类中,使用 `@EnableCaching` 注解开启缓存功能,并使用 `@Bean` 注解创建一个 `CacheManager` 对象: ```java @Configuration @EnableCaching public class CacheConfiguration { @Bean public CacheManager cacheManager() { EhCacheCacheManager cacheManager = new EhCacheCacheManager(); cacheManager.setCacheManager(ehCacheManager().getObject()); return cacheManager; } @Bean public EhCacheManagerFactoryBean ehCacheManager() { EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean(); factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); factoryBean.setShared(true); return factoryBean; } } ``` 在上面的代码中,`EhCacheCacheManager` 是 Spring 提供的一个与 Ehcache 集成的缓存管理器,`EhCacheManagerFactoryBean` 则是 Ehcache 提供的一个工厂类,用于创建 `CacheManager` 对象。`ehcache.xml` 文件则是 Ehcache 的配置文件,用于配置缓存的一些属性,如缓存的最大容量、过期时间等。 最后,在需要使用缓存的方法上添加 `@Cacheable` 注解,如下所示: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override @Cacheable(value = "userCache", key = "#id") public User getUserById(Long id) { return userDao.getUserById(id); } } ``` 在上面的代码中,`@Cacheable` 注解用于将方法的返回值缓存起来,value 属性指定缓存的名称,key 属性指定缓存的键,可以使用 SpEL 表达式指定键的值。当方法被调用时,Spring 会先检查缓存中是否已经存在指定键的值,如果存在,则直接返回缓存中的值,否则执行方法,并将方法的返回值缓存起来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值