码迷,mamicode.com
首页 > 编程语言 > 详细

java 缓存ehcache的使用(使用方式一)

时间:2016-12-28 14:54:01      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:null   class   没有   .com   use   public   使用   create   getc   

实体要序列化

技术分享

resource文件夹下建立 ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
  <diskStore path="java.io.tempdir" />
  <defaultCache maxElementsInMemory="1000" eternal="false"
    timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
  <cache name="ehcacheGO" maxElementsInMemory="10000"
    eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000"
    overflowToDisk="true" />
</ehcache>

建立ehcache的工具类

package com.cjt.utils;

import java.net.URL;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;


public class EhcacheUtil {

  private static final String path = "/ehcache.xml";

  private URL url;

  private CacheManager manager;

  private static EhcacheUtil ehCache;

  private EhcacheUtil(String path) {
    url = getClass().getResource(path);
    manager = CacheManager.create(url);
  }

  public static EhcacheUtil getInstance() {
    if (ehCache== null) {
    ehCache= new EhcacheUtil(path);
   }
    return ehCache;
  }

  public void put(String cacheName, String key, Object value) {
    Cache cache = manager.getCache(cacheName);
    Element element = new Element(key, value);
    cache.put(element);
  }

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

  public Cache get(String cacheName) {
    return manager.getCache(cacheName);
  }

  public void remove(String cacheName, String key) {
    Cache cache = manager.getCache(cacheName);
    cache.remove(key);
   }

 }

===================================================

使用ehcache

 @RequestMapping("/showUser")
 public String toIndex(HttpServletRequest request, Model model) {
  System.out.println("UserController showUser");
  int id = Integer.parseInt(request.getParameter("id"));
  User user = userService.getUserById(id);

  //将查询到的结果放入缓存
  EhcacheUtil.getInstance().put("ehcacheGO", "userEch", user);
  model.addAttribute("user", user);
  return "showUser";
 }
技术分享

 


 @RequestMapping("/getUser")
 public String toEhcahe(HttpServletRequest request, Model model) {
  System.out.println("use cacher");

     //从缓存中取数据
  User user=(User)EhcacheUtil.getInstance().get("ehcacheGO", "userEch");
  model.addAttribute("userCache", EhcacheUtil.getInstance().get("ehcacheGO", "userEch"));
  model.addAttribute("user", user);
  return "showUser";
  }

 技术分享

上面showUser时发送了sql语句,下面getUser时没有发送sql语句说明直接从缓存中取的数据

java 缓存ehcache的使用(使用方式一)

标签:null   class   没有   .com   use   public   使用   create   getc   

原文地址:http://www.cnblogs.com/austinspark-jessylu/p/6229334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!