Spring/Mybtais 整合ehcache - Go语言中文社区

Spring/Mybtais 整合ehcache


整合ehcache使用通过spring集成ehcache,将ehcache交给spring管理。

由于mybatis主要是一套持久层框架,自身并没有较为完善的缓存解决方案,所以我们需要使用第三方缓存框架来完善系统。

1.先对ehcache进行相关介绍

ehcache是一个分布式缓存框架,和redis,memcached,ehcache一类都为分布式缓存(将缓存数据集中管理,这里说的集中管理不是单机的意思,这里也是一个集群的管理(依旧是多台服务器)(例如:redis集群))

首先在mybatis有一个cache接口,如果我们要是使用其他缓存,则必须为该接口寻找一个实现类。其次我们需要将缓存管理交由Spring IOC容器进行管理。

实现类:第三方框架ehcache

<!--分布式缓存框架ehcache -->
<dependency>
	<groupId>net.sf.ehcache</groupId>
	<artifactId>ehcache-core</artifactId>
	<version>${ehcache}</version>
</dependency>

交由springIOC管理,需要使用到spring-support jar包里面的相关类

<!--里面包含spring对于缓存的相关支持-->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
	<version>${org.springframework.version}</version>
</dependency>

2.配置相关配置

在spring配置文件内配置ehcache缓存相关配置,注意添加spring缓存命名空间

<?xml version="1.0" encoding="GBK"?>
<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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">

	<!--开启注解扫描 -->
	<context:component-scan base-package="com.*"></context:component-scan>

	<!-- 应用spring cache注解功能 -->
	<cache:annotation-driven
		cache-manager="cacheManager" />

	<!-- 配置ehcache管理器 -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheCacheManager">
		<property name="cacheManager" ref="ehcache"></property>
	</bean>

	<!--配置缓存管理 -->
	<bean id="ehcache"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation"
			value="classpath:resources/cache/ehcache.xml"></property>
	</bean>

</beans>

配置ehcache配置文件ehcache.xml

<?xml version="1.0" encoding="GBK"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
	updateCheck="false">

     <!--
        diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
        user.home – 用户主目录
        user.dir  – 用户当前工作目录
        java.io.tmpdir – 默认临时文件路径
     -->
	<diskStore
		path="D:\Myself\eclipse\workspace\SSMXML\cache" />

    <!--  设置缓存的默认数据过期策略 -->    
      <defaultCache
          maxElementsInMemory="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          overflowToDisk="true"
          />

        <!--
           defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
         -->
        <!--
          name:缓存名称。
          maxElementsInMemory:缓存最大数目
          maxElementsOnDisk:硬盘最大缓存个数。
          eternal:对象是否永久有效,一但设置了,timeout将不起作用。
          overflowToDisk:是否保存到磁盘,当系统当机时
          timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
          timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
          diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
          diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
          diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
          memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
          clearOnFlush:内存数量最大时是否清除。
          memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
          FIFO,first in first out,这个是大家最熟的,先进先出。
          LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
          LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
        -->

	<defaultCache 
	    maxElementsInMemory="10000" 
	    eternal="false"
		timeToIdleSeconds="120" 
		timeToLiveSeconds="120" 
		overflowToDisk="true" 
		/>

	<cache name="cacheTest" 
	       maxElementsInMemory="1000"
		   eternal="false" 
		   overflowToDisk="true" 
		   timeToIdleSeconds="100"
		   timeToLiveSeconds="200" 
		   />
</ehcache>

3.使用

@Service("userService")
@Transactional(rollbackFor=Exception.class)
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Override
	//在执行增删改操作时,为了保证缓存和数据库信息一致性,会将缓存信息清空
	@CacheEvict(value="cacheTest",allEntries=true)
	public List<User> saveAndView(User user) throws Exception {

		userMapper.insertSelective(user);

		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdLessThan(10);

		List<User> result = userMapper.selectByExample(example);

		return result;
	}

	@Override
	//在查询时,会先在缓存中查找数据,当缓存中数据不存在时,才会执行之后方法查找数据库
	@Cacheable(value="cacheTest")
	public List<User> getUserById(Integer id) throws Exception {
		
		UserExample example = new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(id);

		List<User> result = userMapper.selectByExample(example);

		return result;
	}

}

4.测试

启动项目,访问url 

第一次,创建sqlSession,执行sql语句,返回数据。

第二次,重新访问url,由于并未开启mybatis二级缓存,且第二次访问url系统重新创建了sqlSession实例,所以我们可以保证缓存数据并不可能来自mybatis一级,或二级缓存。可以返现此次访问并未执行相关sql语句,缓存来自ehcache

其次,我们发现在我们配置的缓存资源路径下,出现了缓存文件。

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Stephen_mu/article/details/88597771
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:49:04
  • 阅读 ( 740 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢