1. 程式人生 > >Map實現java快取機制的簡單例項

Map實現java快取機制的簡單例項

快取是java中主要的內容,主要目的是緩解專案訪問資料庫的壓力以及提升訪問資料的效率,以下是通過Map實現java快取的功能,並沒有用cache相關框架。

一、快取管理類 CacheMgr.java

package cache.com;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 *  快取管理類
 * @author Administrator
 *
 */
public class CacheMgr {
	
	 private static Map cacheMap = new HashMap();
	 private static Map cacheConfMap = new HashMap();
	 
	 private static CacheMgr cm = null;
	 
	 //構造方法
	 private CacheMgr(){
	 }
	 
	
	 
	 public static CacheMgr getInstance(){
		  if(cm==null){
		   cm = new CacheMgr();
		   Thread t = new ClearCache();
		   t.start();
		  }
		  return cm;
		 }
	 
	 
	 /**
	  * 增加快取
	  * @param key
	  * @param value
	  * @param ccm 快取物件
	  * @return 
	  */
	 public  boolean addCache(Object key,Object value,CacheConfModel ccm){
		  System.out.println("開始增加快取-------------");
		  boolean flag = false;
		  try {
			  cacheMap.put(key, value);
			  cacheConfMap.put(key, ccm);
			  System.out.println("增加快取結束-------------");
			  System.out.println("now addcache=="+cacheMap.size());
			  flag=true;
		  } catch (Exception e) {
			e.printStackTrace();
		  }
		  
		  return flag;
		 }
	 
	 
	   /**
	    * 獲取快取實體
	    */
	 public Object getValue(String key){
		 Object ob=cacheMap.get(key);
		 if(ob!=null){
			 return ob;
		 }else{
			 return null;
		 }
	 }
	 
	 
	    /**
	     * 獲取快取資料的數量
	     * @return
	     */
	    public int getSize(){
	        return cacheMap.size();
	    }
	 
	    
	    
	 
	 /**
	  * 刪除快取
	  * @param key
	  * @return 
	  */
	 public  boolean removeCache(Object key){
		 boolean flag=false;
		 try {
			  cacheMap.remove(key);
			  cacheConfMap.remove(key);
			  flag=true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		  return flag;
		 }
	 
	 
	 
	 /**
	  * 清除快取的類
	  * 繼承Thread執行緒類
	  */
	 private static class ClearCache extends Thread{
		  public void run(){
		   while(true){
		    Set tempSet = new HashSet();
		    Set set = cacheConfMap.keySet();
		    Iterator it = set.iterator();
		    while(it.hasNext()){
		     Object key = it.next();
		     CacheConfModel ccm = (CacheConfModel)cacheConfMap.get(key);
		     //比較是否需要清除
		     if(!ccm.isForever()){
		      if((new Date().getTime()-ccm.getBeginTime())>= ccm.getDurableTime()*60*1000){
		       //可以清除,先記錄下來
		       tempSet.add(key);
		      }
		     }
		    }
		    //真正清除
		    Iterator tempIt = tempSet.iterator();
		    while(tempIt.hasNext()){
		     Object key = tempIt.next();
		     cacheMap.remove(key);
		     cacheConfMap.remove(key);
		     
		    }
		    System.out.println("now thread================>"+cacheMap.size());
		    //休息
		    try {
		     Thread.sleep(60*1000L);
		    } catch (InterruptedException e) {
		     e.printStackTrace();
		    }
		   }
		  }
		 }
	 
	 
	 
	 
}

二、快取屬性類 CacheConfModel.java

package cache.com;
/**
 * 快取屬性類
 * @author Administrator
 *
 */
public class CacheConfModel implements java.io.Serializable{
	
	 private long beginTime;//快取開始時間
	 private boolean isForever = false;//是否持久
	 private int durableTime;//持續時間
	 
	 public long getBeginTime() {
		  return beginTime;
		 }
		 public void setBeginTime(long beginTime) {
		  this.beginTime = beginTime;
		 }
		 public boolean isForever() {
		  return isForever;
		 }
		 public void setForever(boolean isForever) {
		  this.isForever = isForever;
		 }
		 public int getDurableTime() {
		  return durableTime;
		 }
		 public void setDurableTime(int durableTime) {
		  this.durableTime = durableTime;
		 }

}

三、配置啟動專案時自動載入 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<servlet>
	  <servlet-name>testCache</servlet-name>
	  <servlet-class>cache.com.Cservlet</servlet-class>
	</servlet>
	<servlet-mapping>
	  <servlet-name>testCache</servlet-name>
	  <url-pattern>/testCache.do</url-pattern>
	</servlet-mapping>
	
	<servlet>
		<servlet-name>cacheinitservlet</servlet-name>
		<servlet-class>cache.com.LoadCache</servlet-class>
		<load-on-startup>2</load-on-startup>
	</servlet>
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

四、自動載入快取的類 LoadCache.java

  在此類中實現你想要初始化的快取資料

package cache.com;

import java.util.Date;
import javax.servlet.http.HttpServlet;

import cache.com.CacheConfModel;
import cache.com.CacheMgr;
/**
 * 專案啟動時預設載入快取資料類
 * @author Administrator
 */
public class LoadCache extends HttpServlet{
	

	public void init(){
		addData();
	}
	
	/**
	 * 專案啟動時載入快取
	 */
	public void addData(){
		System.out.println("進入載入快取addData()………………。");
		CacheMgr cm=CacheMgr.getInstance();
		CacheConfModel cModel=new CacheConfModel();
		Date d=new Date();
		cModel.setBeginTime(d.getTime());
		cModel.setDurableTime(60);
		cModel.setForever(true);
		cm.addCache("kk", "123", cModel);//在快取加值
	}
	
}

五、寫一個測試類 Cservlet.java,我在這裡寫了一個servlet類進行測試的

package cache.com;

import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 測試讀取、新增快取資料等
 * @author Administrator
 */
public class Cservlet extends HttpServlet{
	
	public void service(HttpServletRequest request,HttpServletResponse response){
		try {
			System.out.println("進入servlet類............");
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");   //3.設定響應型別

			PrintWriter out = response.getWriter();
			
			
			CacheMgr cm=CacheMgr.getInstance();
			
			int numm=cm.getSize();//獲取快取個數
			Object ob=cm.getValue("kk");
			System.out.println("numm===========//======"+numm);
			out.println("快取個數為:"+numm);
			out.println("快取數值:value===="+ob);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	
		
	}

}

六、寫一個簡單的按鈕頁面 index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <form action="testCache.do" method="post">
      <button type="submit" >獲取快取資料</button>
    
    </form>
  </body>
</html>

啟動專案後點擊按鈕 “獲取快取資料”後,出現如下圖說明快取成功併成功取值了