Spring和Ehcache整合详解

本文详细介绍了如何将Spring与Ehcache进行整合,包括Ehcache的特性、Spring对缓存的支持、配置步骤、业务逻辑中的缓存应用,以及在实际操作中需要注意的事项。通过示例代码展示了如何在Service中使用缓存提高数据库操作效率,并提供了测试方法。文章还提到了SpringMVC配置可能导致的问题及解决方案。
摘要由CSDN通过智能技术生成

Spring和Ehcache整合详解

一、官方主页

Spring Cache

二、概述

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点.

Spring 提供了对缓存功能的抽象:即允许绑定不同的缓存解决方案(如Ehcache),但本身不直接提供缓存功能的实现。它支持注解方式使用缓存,非常方便。

Ehcache是使用的是本地的内存做缓存,而redis则是部署在另一个server的缓存服务器,一般可以用redis + ehcache做两级缓存。

Git地址:
Gitee

项目地址:
品茗IT-首发

品茗IT 提供在线支持:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

三、开始搭建

3.1 依赖Jar包
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.pomit</groupId>
		<artifactId>SpringWork</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>Ehcache</artifactId>
	<packaging>jar</packaging>
	<name>Ehcache</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<!-- ehcache 相关依赖 -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>
		<dependency>
			<groupId>cn.pomit</groupId>
			<artifactId>Mybatis</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>Ehcache</finalName>
	</build>
</project>

父pom管理了所有依赖jar包的版本,地址:
https://www.pomit.cn/spring/SpringWork/pom.xml

3.2 spring配置文件

spring-ehcache.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/context      
        http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />
		<context:component-scan base-package="cn.pomit.springwork">
	</context:component-scan>
	
	<bean id="ehcache"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation" value="classpath:ehcache/ehcache.xml" />
	</bean>

	<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
		<property name="cacheManager" ref="ehcache" />
	</bean>

	<cache:annotation-driven cache-manager="cacheManager" />
	
	<bean id="cacheService" class="cn.pomit.springwork.ehcache.service.CacheService">
		<property name="userInfoService" ref="userInfoService" />
	</bean>
</beans>

这里,声明了EhCacheManagerFactoryBean的bean,读取ehcache.xml的配置。ehcache.xml是用来配置缓存的名字。只有配置的名字才可以在代码中被使用。

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/ehcache"/>

  <!-- 默认缓存 -->
  <defaultCache
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          maxEntriesLocalDisk="10000000"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU"/>

  <!-- userCache缓存 -->
  <cache name="userCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="0"
         timeToLiveSeconds="1000"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>
</ehcache>
3.3 业务逻辑进行缓存

这里,我们定义一个service,CacheService对数据库的操作进行缓存,UserInfoService是依赖包Mybatis项目中定义的一个数据库访问的service,这里就不写了,可以在快速构建Spring项目工具中查看Mybatis组合组件的代码。

CacheService :

package cn.pomit.springwork.ehcache.service;

import org.springframework.cache.annotation.Cacheable;

import cn.pomit.springwork.mybatis.domain.UserInfo;
import cn.pomit.springwork.mybatis.service.UserInfoService;

public class CacheService {
	UserInfoService userInfoService;

	@Cacheable(value = "userCache", key = "#root.targetClass.simpleName+'-'+#root.methodName+'-'+#userName")
	public UserInfo getUserInfoByUserName(String userName) {
		return userInfoService.getUserInfoByUserName(userName);
	}

	public UserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}
	
	
}
3.4 注意事项

CacheService在这里没有用@Service作注解,而是放在xml定义了一个bean,这是因为,@Service注解不能被动态代理,导致缓存无效,经过多次实验,放在xml里是可以被代理到,并使缓存生效。

这个原因是:

  • Springmvc和Spring配置的扫描路径没有分离开来,重复扫描导致了Spring扫描过程使用了代理,但是Springmvc过程冲掉了这个bean。

  • 如果Springmvc使用context:include-filter配置了只扫描Controller和RestController注解就可以解决这个问题。

  • 《Spring和Spring Mvc 5整合详解》这篇已经修正了Springmvc的配置

3.5 测试

我们可以定义一个web请求控制器EhcacheRest来做简单测试,这里将忽略Springmvc的配置,配置MVC可以在SpringMvc4 配置方法中查看,SpringMvc5 配置方法中查看。

EhcacheRest:

package cn.pomit.springwork.ehcache.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springwork.ehcache.service.CacheService;
import cn.pomit.springwork.mybatis.domain.UserInfo;

@RestController
@RequestMapping("/ehcache")
public class EhcacheRest {

	@Autowired
	private CacheService cacheService;

	@RequestMapping(value = "/test/{name}", method = { RequestMethod.GET })
	public UserInfo test(@PathVariable("name") String name) {
		return cacheService.getUserInfoByUserName(name);
	}

}

详细完整及测试代码,可以在《品茗IT-Spring和Ehcache整合详解》中查看,也可以在Spring组件化构建中选择并下载。

快速构建项目

Spring组件化构建

喜欢这篇文章么,喜欢就加入我们一起讨论Spring技术吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值