`
baobeituping
  • 浏览: 1041277 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

OSCache缓存技术(6)【实例】

阅读更多

本实例将模仿一个JSP页面从数据库中取得一个LIST集合的数据,模型是模拟一个新闻发布页面去后台取得信息,系统设定10秒钟更新一次缓存,而前台页面每隔5秒打印一次集合信息。

 <1>POJO缓存实现

1.缓存的基类BaseCache

package com.test;

import java.util.Date;

import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

public class BaseCache extends GeneralCacheAdministrator {
 // 过期时间(单位为秒);
 private int refreshPeriod;

 // 关键字前缀字符;
 private String keyPrefix;

 private static final long serialVersionUID = -4397192926052141162L;

 public BaseCache(String keyPrefix, int refreshPeriod) {
  super();
  this.keyPrefix = keyPrefix;
  this.refreshPeriod = refreshPeriod;
 }

 // 添加被缓存的对象;
 public void put(String key, Object value) {
  this.putInCache(this.keyPrefix + "_" + key, value);
 }

 // 删除被缓存的对象;
 public void remove(String key) {
  this.flushEntry(this.keyPrefix + "_" + key);
 }

 // 删除所有被缓存的对象;
 public void removeAll(Date date) {
  this.flushAll(date);
 }

 public void removeAll() {
  this.flushAll();
 }

 // 获取被缓存的对象;
 public Object get(String key) throws Exception {
  try {
   return this.getFromCache(this.keyPrefix + "_" + key,
     this.refreshPeriod);
  } catch (NeedsRefreshException e) {
   
   this.cancelUpdate(this.keyPrefix + "_" + key);
   throw e;
  }

 }
 private static BaseCache cache;
 public static BaseCache getInstance()
 {
  if(cache==null)
  {
   cache = new BaseCache("count",10);
  }
  
  return cache;
 }

}
2.缓存的管理类CacheUser

package com.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CacheUser {
 private BaseCache newsCache;
 private static CacheUser instance;     
  
    private static Object lock = new Object();
 private CacheUser() {     
   
        //这个根据配置文件来,初始BaseCache而已;     
 
        newsCache = new BaseCache("news",10); //在这里10表示的10秒钟更新一次缓存 
  
    }  
 public List<String> getUser(String newsID) {     
  
        try {     
         List<String> list = null;
         list = (List<String>) newsCache.get(newsID);
            return list;      
      //因为是10秒钟更新一次缓存,所以每隔10秒后newsCache.get(newsID)就会为空,抛出异常,重新去数据库取得数据
        } catch (Exception e) {     
 
            System.out.println("getNews>>newsID["+newsID+"]>>"+e.getMessage());     
 
            Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8";
        String user = "root";
        String pwd = "root";
        
        List<String> lists =new ArrayList<String>();
        try
     {
      String sql = "select * from kindergarden_user";
      Class.forName(driver);
      con = DriverManager.getConnection(url,user,pwd);
      stmt = con.createStatement();
      rs = stmt.executeQuery(sql);
      while(rs.next())
      {
       String name = rs.getString("Name");
       lists.add(name);
      }
      
      newsCache.put("userlist",lists); //重新取得数据以后,放到缓存中
      
     }
     catch(Exception e3)
     {
      e3.printStackTrace();
     }
        finally
        {
         try
         {
         
         }
         catch(Exception ee)
         {
          try {
      rs.close();
      stmt.close();
      con.close();
     } catch (Exception exx) {
      exx.printStackTrace();
     }
         }
        }   
            return lists;     
 
        }     
 
    }   
 public void putUser(User news) { newsCache.put(news.getId()+"",news);      }  
 //通过单线程的方式取得缓存的对象
  public static CacheUser getInstance(){     
   
         if (instance == null){     
  
             synchronized( lock ){     
  
                 if (instance == null){     
  
                     instance = new CacheUser();     
  
                 }     
  
             }     
  
         }     
  
         return instance;     
  
    }
  public void removeUser(String newsID) {  newsCache.remove(newsID);       } 
  public void removeAllUsers() {     
   
         newsCache.removeAll();     
  
     }
}
3.前端的JSP页面userlist.jsp

<%@ page language="java" import="java.util.*,java.sql.*,com.test.*" pageEncoding="GB2312" isELIgnored="false"%>
<%@ taglib prefix="s" uri="/WEB-INF/classes/oscache.tld" %>
<%
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>
   <%
    
    
    %>
   

 <%
     List<String> list = null;
    CacheUser cm=CacheUser.getInstance(); 

    //通过单利模式取得缓存对象,然后从缓存中取得LIST集合,前端页面就不用管集合是从数据库还是缓存中得到了,由缓存管理的类去进行管理
     for (int i = 0; i < 1000; i++) {
       
     try {  
        list = (List<String>)cm.getUser("userlist");
        System.out.println(list);
         if(i==10){  
  
               //删除缓存id的对象  
  
               cm.removeUser("userlist");  
  
             }           
   
             if(i==20){  
   
                //删除所有缓存的对象  
   
                cm.removeAllUsers();  
   
             }   
               Thread.sleep(5000);  
       
            } catch (Exception e) {  
  
            }  
     }
  
  %>


   
   
  </body>
</html>

<2>JSP页面缓存实现

1.在WEB.XML文件中配置

<taglib>
  <taglib-uri>oscache</taglib-uri>
  <taglib-location>/WEB-INF/classes/oscache.tld</taglib-location>
 </taglib>

2.编写index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="cache" uri="oscache" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>

没有缓存的日期: <%= new Date() %><p>
<!--自动刷新-->
<cache:cache time="10">
每30秒刷新缓存一次的日期: <%= new Date() %>

<!--该段代码处的时期是10秒钟清空一次,也就是10秒钟取得一次,你在10秒内刷新index.jsp该时间是不变的。-->
</cache:cache>
<!--手动刷新-->
<cache:cache key="testcache">
手动刷新缓存的日期: <%= new Date() %> <p>

<!--该段代码处的时间永远都不变,除非你手动刷新该处的时间,要么该时间永远保存在缓存中。-->
</cache:cache>
<a href="cache2.jsp">手动刷新</a>

</body>
</html>

3.cache2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="cache" uri="oscache" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>

缓存已刷新...<p>

<cache:flush key="testcache" scope="application"/>

<a href="index.jsp">返回</a>

</body>
</html>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics