简易的 Cache 使用
Posted lifan12589
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简易的 Cache 使用相关的知识,希望对你有一定的参考价值。
java :
package com.ehCache; import java.io.IOException; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.alibaba.fastjson.JSONArray; import wfc.service.database.RecordSet; import wfc.service.database.SQL; /** * 数据库中查询市区,记在缓存中 * */ @Controller public class ehCache { private Cache cache; @Autowired private CacheManager cacheManager; @PostConstruct public void init() { this.cache = cacheManager.getCache("designatedDict"); } @RequestMapping("/ehCache/jsonCache.do") public void jsonCache (HttpServletRequest request,HttpServletResponse response) throws IOException{ request.setCharacterEncoding("UTF-8"); response.setContentType("text/plain; charset=UTF-8"); JSONArray jsonArray = new JSONArray(); String sheng = request.getParameter("sheng"); if (this.cache.get(sheng) == null|| this.cache.get(sheng).get() == null) { String sql =""; Object[] objects; if(sheng !=null){ sql = "select * from SHI_QU where SHENG = ?"; objects = new Object[] {sheng}; RecordSet rs = SQL.execute(sql, objects); while (rs.next()) { com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject(); String code = rs.getString("SHI_ID"); String name = rs.getString("SHI"); json.put("code", code); json.put("name", name); jsonArray.add(json); } this.cache.put(sheng, jsonArray); System.out.println("jsonArray---->"+jsonArray); System.out.println("this.cache---->"+this.cache); System.out.println((JSONArray) this.cache.get(sheng).get()); } }else{ jsonArray = (JSONArray) this.cache.get(sheng).get(); } response.getWriter().print(jsonArray.toString()); } }
cache.xml 配置:
路径:src/main/resources/ehcache.xml
<ehcache> <diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> <cache name="designatedDict" maxElementsInMemory="100000" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"> </cache> </ehcache>
以上是关于简易的 Cache 使用的主要内容,如果未能解决你的问题,请参考以下文章
关于mysql驱动版本报错解决,Cause: com.mysql.jdbc.exceptions.jdbc4Unknown system variable ‘query_cache_size(代码片段