ssm+ehcache入门实战

ssm的整合不做介绍,主要介绍ehcache在项目中的应用

1、pom.xml引入ehcache jar包

    
    
        net.sf.ehcache
        ehcache-core
        2.6.6
    

2、新建ehcache.xml文件并配置



 
 
 
    
  
          
 
           
 
      


[点击并拖拽以移动]
​

3、编写ehcache工具类EhCacheUtil2.java

package com.shp.util;

import java.net.URL;
import javax.annotation.PostConstruct;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@Component
@Scope
public class EhCacheUtil2 {
	private CacheManager manager;
	private URL url;
@PostConstruct
public void init() {
	url = getClass().getResource("/ehcache.xml"); 
	manager = CacheManager.create(url);  
}
public void put(String tableName, String key, Object value) {
    Cache cache = manager.getCache(tableName);
    if(cache == null) {
    	return;
    }
    Element element = new Element(key, value);
    cache.put(element);
}

public Object get(String tableName, String key) throws Exception{
    Cache cache = manager.getCache(tableName);
    if(cache == null) {
    	return null;
    }
    Element element = cache.get(key);
    return element == null ? null : element.getObjectValue();
}

public void remove(String tableName, String key) {
    Cache cache = manager.getCache(tableName);
    if(cache == null) {
    	return;
    }
    cache.remove(key);
}
public void clear(String tableName) {
	 Cache cache = manager.getCache(tableName);
	 if(cache == null) {
	    	return;
	    }
	 cache.removeAll();
}

}

4、实体类Student.java

package com.shp.bean;

public class Student {
 
  private int id;
  private String name;
  private int age;
  private String gender;
  private String grade;
  
  public Student(int id, String name, int age, String gender, String grade) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.gender = gender;
		this.grade = grade;
	}
  
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
public String getGender() {
	return gender;
}
public void setGender(String gender) {
	this.gender = gender;
}
public String getGrade() {
	return grade;
}
public void setGrade(String grade) {
	this.grade = grade;
}
@Override
public String toString() {
	return "Student [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + ", grade=" + grade + "]";
}
  
}

5、Dao层接口StudentDao.java

package com.shp.dao;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.shp.bean.Student;

public interface StudentDao {
	 String TABLE_NAME = "tbl_student";
	  void insertStudent(Student stu);
	
	  void deleteStudent(String name);
	  
	  @Update({"Update",TABLE_NAME,"set age=#{student.age},grade=#{student.grade}","WHERE name=#{student.name}"})
	  void updateStudentByName(@Param("student") Student student);
	  
	  @Select({"SELECT * FROM",TABLE_NAME,"WHERE name=#{name}"})
	  Student findStuByName(@Param("name") String name);
	  
	  @Select({"SELECT * FROM",TABLE_NAME})
	  List QueryAll();

}

6、Service层接口StudentService.java

​

package com.shp.service;

import java.util.List;
import com.shp.bean.Student;

public interface StudentService {

	  void insertStudent(Student stu,String tableName);
		
	  void deleteStudent(String name,String tableName);
	  
	  void updateStudentByName(Student stu,String tableName);
	  
	  Student findStuByName(String name,String tableName);
	  
	  List QueryAll();
	  
}

[点击并拖拽以移动]
​

7、Service层接口实现StudentServiceImp.java

package com.shp.service.Imp;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shp.bean.Student;
import com.shp.dao.StudentDao;
import com.shp.service.StudentService;
import com.shp.util.EhCacheUtil2;

@Service
public class StudentServiceImp implements StudentService{
		@Autowired
		private StudentDao stuDao;
	    @Autowired
	    private EhCacheUtil2 ehCacheUtil;

		@Override
		public void insertStudent(Student stu,String tableName) {
			// TODO Auto-generated method stub
			stuDao.insertStudent(stu);		
		}

		@Override
		public void deleteStudent(String name,String tableName) {
			// TODO Auto-generated method stub
		}

		@Override
		public void updateStudentByName(Student stu,String tableName) {
			// TODO Auto-generated method stub
			stuDao.updateStudentByName(stu);
			String key=stu.getName();
			ehCacheUtil.remove(tableName, key);
		}

		@SuppressWarnings("finally")
		@Override
		public Student findStuByName(String name,String tableName) {
			// TODO Auto-generated method stub
			Student student=null;
			try {
				student = (Student)ehCacheUtil.get(tableName, name);
				if(student==null) {
				student=stuDao.findStuByName(name);
				ehCacheUtil.put(tableName, name, student);
			} 
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally {
				return student;
			}
		}

		@Override
		public List QueryAll() {
			// TODO Auto-generated method stub
			return stuDao.QueryAll();
		} 
}

8、测试TestController.java

package com.shp.controller;

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.RequestMethod;
import com.shp.bean.Student;
import com.shp.dao.StudentDao;
import com.shp.service.Imp.StudentServiceImp;
@Controller
public class TestController {
	@Autowired
	private StudentDao sd;
	@Autowired
	private StudentServiceImp ssi;
	 @RequestMapping(value = "/test",  method = RequestMethod.GET)
	    public String index(){
	    System.out.println("==测试去数据库中查找===");
	    long currentTime1=   System.currentTimeMillis();
	    Student  stu1=sd.findStuByName("小明");
	    long currentTime2=   System.currentTimeMillis();  
	    System.out.println("stu1="+stu1+"使用了"+(currentTime2-currentTime1)+"毫秒");
	    
	    System.out.println("==测试第一次使用缓存方法查找==");
	    long currentTime3=   System.currentTimeMillis(); 
	    Student stu2 = ssi.findStuByName("小明", "tbl_student");
	    long currentTime4=   System.currentTimeMillis(); 
	    System.out.println("stu2="+stu2+"使用了"+(currentTime4-currentTime3)+"毫秒");
	    
	    System.out.println("==测试第二次使用缓存方法查找==");
	    long currentTime5=   System.currentTimeMillis(); 
	    Student stu3 = ssi.findStuByName("小明", "tbl_student");
	    long currentTime6=   System.currentTimeMillis(); 
	    System.out.println("stu3="+stu3+"使用了"+(currentTime6-currentTime5)+"毫秒");
	    
	    System.out.println("==测试update==begin==");
	    Student stu4=new Student(1, "小明", 20, "男", "大一");
	    sd.updateStudentByName(stu4);
	    System.out.println("==测试update去缓存中查找==");
	    Student stu5 = ssi.findStuByName("小明", "tbl_student");
	    System.out.println("stu5="+stu5);
	    System.out.println("==测试update去数据库中查找==");
	    Student stu6=sd.findStuByName("小明");
	    System.out.println("stu6="+stu6);
	    System.out.println("==测试update==finished==");
	    
	    return "test";
	    }
}

9、测试结果

ssm+ehcache入门实战_第1张图片

10、总结

       从结果中很清晰的看出从缓存中查找数据要比访问数据库要快,需要注意的是update操作需要及时清除缓存,否则在缓存有效期内,查出的数据还是update之前的。同理,delete操作,也是如此。

 

你可能感兴趣的:(缓存框架)