springboot整合ehcache的两种方法

 

一、使用注解的方式(更简洁,代码量少)

1、引入pom依赖,springboot缓存支持和ehcache

<!-- Spring Boot 缓存-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

2、启动类添加@EnableCaching注解以及application.properties配置文件增加配置

#ehcache配置
spring.cache.ehcache.config=classpath:/ehcache.xml

3、添加ehcache.xml文件在resources文件夹下

<?xml version="1.0" encoding="utf-8"?>
<ehcache name="max" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <!--支持内存和磁盘两种存储-->
    <diskStore path="java.io.tmpdir"/><!--path表示路径-->
    <defaultCache
            maxElementsInMemory="100000"
            eternal="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="0"
            overflowToDisk="true"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
    <!--diskPersistent 是否在磁盘上实例化,重启jvm后失效-->
    <!--diskExpiryThreadIntervalSeconds 检测缓存对象的线程,运行的时间间隔-->
    <cache name="users"
           maxElementsInMemory="10000"
           eternal="false"
           overflowToDisk="true"
           timeToIdleSeconds="1800000"
           timeToLiveSeconds="0"
           memoryStoreEvictionPolicy="LFU" >

    </cache>
    <!--maxElementsInMemory最大允许存储10000个元素-->
    <!--eternal是否为永久,否-->
    <!--timeToIdleSeconds对象在失效前,闲置的最大时间-->
    <!--timeToLiveSeconds对象的最大生存时间,从创建开始最大时间,只在eternal为false时生效-->
    <!--memoryStoreEvictionPolicy内存满后的清空策略,有三种FIFO,LFU,LRU-->
    <!--FIFO 先进先出
        LFU 使用次数最少(对象有计数值count)
        LRU 创建时间最早的清空(对象有时间戳)
    -->
</ehcache>

4、由于需要实体类支持缓存中的磁盘存储,所以实体类都要实现Serializable可序列化接口

5、使用注解实现缓存功能:@Cacheable(添加操作),@CachePut(修改操作),@CacheEvict(删除操作)

package com.sumengnan.test.service;

import com.sumengnan.dao.UserDao;
import com.sumengnan.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional//添加事务
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	@Override
	@Cacheable(value="users",key = "#id")
	//value表示缓存的名称
	//key表示缓存的key,可以为空,也可以用el表达式。支持四种:#参数名(#id),#p+参数index(#p0),#参数的属性(user.id),#p+参数index(#p0.id)
	//condition表示缓存的条件,可以为空,也可以用el表达式,例如:condition="#user.id>0"(只缓存id大于0的)
	public User get(Long id) {
		User user=userDao.getUser(1L);
		System.out.println("1111111111111111111111111");
		return user;
	}

	@Override
	@CachePut(value = "users")
	//和@Cacheable差不多:唯一的区别是@Cacheable会先判断缓存元素是否存在,再决定是直接返回还是缓存,而@CachePut总是会缓存数据
	public User save(Long id) {
		User user=new User();
		System.out.println("222222");
		return user;
	}

	@Override
	@CacheEvict(value="users",key = "#id")
	//value表示缓存的名称
	//key表示缓存的key,可以为空,也可以用el表达式。支持四种:#参数名(#id),#p+参数index(#p0),#参数的属性(user.id),#p+参数index(#p0.id)
	//allEntries表示是否需要清除所有的元素,默认为false
	//beforeInvocation表示是否需要在执行此删除方法之前删除缓存
	public void delete(Long id) {
		System.out.println("33333333333");
	}

	//四、@Caching
	//可以通过@Caching注解组合多个注解集合在一个方法上
	//这个注解可以组合多个注解,从而实现自定义注解

	//自定义注解
/*	@Target({ElementType.TYPE, ElementType.METHOD})
	@Retention(RetentionPolicy.RUNTIME)
	@Cacheable(value="users")
	public @interface MyCacheable {
	}*/
}

 

 

二、普通方式(更灵活)


1、引入pom依赖,ehcache

<!-- Ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

 2、application.properties配置文件增加配置(同上)

3、添加ehcache.xml文件在resources文件夹下(同上)

4、service方法使用如下:

package com.sumengnan.test.service;

import com.sumengnan.dao.UserDao;
import com.sumengnan.entity.User;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional//添加事务
public class UserServiceImpl2 implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public User get(Long id) {
        Cache cache = cacheManager.getCache("users");
        Element element = cache.get(id);
        if(element!=null){//如果缓存中存在
            return (User)element.getObjectValue();//直接取缓存
        }else{
            User user=userDao.getUser(1L);
            //数据库查出后,存储到缓存
            Element element2 = new Element(id, user);
            cache.put(element2);
            return user;
        }
    }

    @Override
    public User save(Long id) {
        User user=new User();
        //直接存储缓存
        Cache cache = cacheManager.getCache("users");
        Element element2 = new Element(id, user);
        cache.put(element2);
        return user;
    }

    @Override
    public void delete(Long id) {
        Cache cache = cacheManager.getCache("users");
        cache.remove(id);
    }

}


 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值