您的位置:首页 > 编程语言 > Java开发

Spring缓存简单介绍(Spring Cache)

2014-06-17 23:44 676 查看
对spring Cache做了个了解,性能非常强悍。而且使用非常简答。下面有各个部分完整的代码。处理缓存的主要逻辑再ServiceImpl中!!

先看下不使用spring Cache查询10次所发出的语句

第1次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第2次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第3次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第4次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第5次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第6次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第7次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第8次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第9次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第10次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
再看下使用spring Cache后查询10次所发出的语句

第1次查询
Hibernate: select student0_.Id as Id0_, student0_.name as name0_, student0_.addr as addr0_ from student student0_ where student0_.Id=?
第2次查询
第3次查询
第4次查询
第5次查询
第6次查询
第7次查询
第8次查询
第9次查询
第10次查询

可见效率提高不少。

首先要把spring常见的几个包导入到项目中

spring 3.1 以上,都支持 spring cache。其中 spring-context-*.jar 包含了 cache 需要的类。

Dao:

package com.ibm.bmcc.qixin.redis.dao;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.ibm.bmcc.qixin.redis.model.Student;

/**
* 缓存测试   dao
* @author zhoudong
*
*/
@Repository
public class StudentDao extends HibernateDaoSupport{
@Resource(name = "sessionFactory")
// 注入 按名称装配
public void setSuperSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
/**
* 获取Student实体,String Cache测试
* @param id
* @return
*/
public Student getStudent(String id){
String hql = "from Student where id = ?";
return (Student) getHibernateTemplate().find(hql, id).get(0);
}
/**
* 缓存更新
* @param student
*/
public void updateStudent(Student student) {
StringBuilder hql = new StringBuilder("update Student set");
if(StringUtils.isNotBlank(student.getName())){
hql.append(" name='");
hql.append(student.getName()).append("'");
}
if(StringUtils.isNotBlank(student.getAddr())){
hql.append(", addr = ");
hql.append(student.getAddr());
}
hql.append("where id = '").append(student.getId()).append("'");
Query query = getSession().createQuery(hql.toString());
query.executeUpdate();
}
}


Service:

package com.ibm.bmcc.qixin.redis.service;

import org.springframework.stereotype.Service;

import com.ibm.bmcc.qixin.redis.model.Student;

/**
* redis测试
* @author zhoudong
*
*/
@Service
public interface StudentService {
/**
* 缓存测试
* @param id
* @return
*/
public Student getStudent(String id);
/**
* 更新缓存测试
* @param student
* @return
*/
public void updateStudent(Student student);
/**
* 清空缓存
*/
public void reload();
}


ServiceImpl:

package com.ibm.bmcc.qixin.redis.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.ibm.bmcc.qixin.redis.dao.StudentDao;
import com.ibm.bmcc.qixin.redis.model.Student;
import com.ibm.bmcc.qixin.redis.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService{
@Resource
private StudentDao studentDao;

@Cacheable(value="redisCache")// 使用了一个缓存名叫 redisCache
public Student getStudent(String id) {
return studentDao.getStudent(id);
}

@CacheEvict(value="redisCache",key="#student.getName()")//更新缓存
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}

@CacheEvict(value="redisCache",allEntries=true)//清空缓存
public void reload() {
}

}


# 号代表这是一个 SpEL 表达式,此表达式可以遍历方法的参数对象,具体语法可以参考 Spring 的相关文档手册。

value是必须参数,类似于存在哪个缓存,key是可选参数,默认是空,

action:

package com.ibm.bmcc.qixin.redis.view;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ibm.bmcc.qixin.redis.model.Student;
import com.ibm.bmcc.qixin.redis.service.StudentService;
/**
* cache 测试action
* @author zhoudong
*
*/
@Controller
public class RedisAction {
@Autowired
private StudentService studentService;
/**
* 缓存测试
* @return
*/
@RequestMapping("redisCache")
public @ResponseBody Map<String, String> redisCache(){
Student student = null;
for(int i=0; i<10; i++){
System.out.println("第" + (i + 1) + "次查询");
student = studentService.getStudent("qwqw");
}

Map<String,String> mav = new HashMap<String, String>();
mav.put("name", student.getName());
mav.put("addr", student.getAddr());
return mav;
}
/**
* 更新缓存
* @return
*/
@RequestMapping("updateCache")
public @ResponseBody Map<String, String> updateCache(){
Student student = null;
Student students = new Student();
students.setName("mmm");
students.setId("qwqw");
studentService.updateStudent(students);
student = studentService.getStudent("qwqw");

Map<String,String> mav = new HashMap<String, String>();
mav.put("name", student.getName());
mav.put("addr", student.getAddr());
return mav;
}
/**
* 清空缓存
* @return
*/
@RequestMapping("reload")
public @ResponseBody Map<String, String> reload(){
studentService.reload(); //清空缓存后再请求10次

Student student = null;
for(int i=0; i<10; i++){
System.out.println("第" + (i + 1) + "次查询");
student = studentService.getStudent("qwqw");
}

Map<String,String> mav = new HashMap<String, String>();
mav.put("name", student.getName());
mav.put("addr", student.getAddr());
return mav;
}
}


既然是spring Cache 配置文件肯定是少不了的。。

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

<!-- cache  start -->
<cache:annotation-driven /><!-- 缓存必须用的,启用缓存 -->
<bean id="studentService" class="com.ibm.bmcc.qixin.redis.service.impl.StudentServiceImpl"/>

<!-- generic cache manager -->
<bean id="cacheManager"
class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="default" />

<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="redisCache" />
</set>
</property>
</bean>
<!-- cache end -->
</beans>


<cache:annotation-driven />启动缓存 必配参数

刚开始了解,初步了解了下简单的,明天会做下更复杂的,请关注下一篇博客。

最终目的是为了spring Cache 和redis结合使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring 缓存