最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java 利用Map做缓存一个简单实例
时间:2013-11-27 编辑:简简单单 来源:一聚教程网
有时候需要将一批数据缓存,并且按照最近最少使用的规则淘汰。这时候就应该想到LRUMap。
LRUMap是一种尺寸固定的Map,当它的容量达到最大时采用最近最少使用的规则淘汰相应的元素。
代码如下 | 复制代码 |
LRUMap cache = newLRUMap(5); cache.put("01", "news 1"); cache.put("02", "news 2"); cache.put("03", "news 3"); cache.put("04", "news 4"); cache.put("05", "news 5"); String news1 = (String)cache.get("01"); String news2 = (String)cache.get("02"); String news3 = (String)cache.get("04"); String news4 = (String)cache.get("03"); String news5 = (String)cache.get("02"); String news6 = (String)cache.get("05"); cache.put("06", "news 6"); Iterator it = cache.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry = (Map.Entry)it.next(); System.out.println(entry.getValue()); } |
LazyMap:当你需要获取某个键值但发现该键值不存在时自动填充该键值,那就该考虑使用LazyMap,LazyMap采用了装饰模式装饰一个Map,并采用一个Transformer来决定当键值不存在时填充的规则(或者Factory)。
代码如下 | 复制代码 |
Transformer reverseString = newTransformer(){ |
综合使用LRUMap和LazyMap:
代码如下 | 复制代码 |
Transformer reverseString = newTransformer(){ |
当然可以在Transformer里可以做任何事,比如从网站爬取数据,并转换成相应的对象等。
如下代码从pchome的ip地址库中查询IP地址,首先定义一个ArticleTransformer对象,每次根据传入的参数从一个URL查询数据并返回。
代码如下 | 复制代码 |
public class ArticleTransformer implements Transformer { protected final static int BUF_SIZE = 300; protected String queryURL; public String getQueryURL(){return queryURL;} public void setQueryURL(String queryURL){this.queryURL = queryURL;} protected long timeOut; public long getTimeOut(){return timeOut;} /** * @param timeOut 单位:ms */ public void setTimeOut(long timeOut){this.timeOut = timeOut;} public Object transform(Object obj){ ArticleRetriever retriever = new ArticleRetriever((String)obj); try{ Thread thread = new Thread(retriever); thread.start(); thread.join(timeOut); //Thread.sleep(3*1000); }catch(InterruptedException e){ System.out.println("url request time out."); } return retriever.getResponse(); } public class ArticleRetriever implements Runnable{ private String name; private String response; public ArticleRetriever(String name){ this.name = name; } public String getResponse(){ return this.response; } public void run(){ HttpURL url = null; try{ HttpClient client = new HttpClient(); url = new HttpURL(queryURL+name); GetMethod getMethod = new GetMethod(url.toString()); getMethod.getParams().setContentCharset("UTF-8"); client.executeMethod(getMethod); response = getMethod.getResponseBodyAsString(); }catch(Exception e){ System.out.println("Error get Article " + url); } } } } |
然后如下代码调用
代码如下 | 复制代码 |
String queryURL = "http://whois.pconline.com.cn/ip.jsp?ip=";
|
最后输出如下的结果:
江苏省泰州市(泰兴)电信
河北省保定市电信
Internet保留地址
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24
- Vue中的路由配置项meta使用解读 10-24
- SpringBoot自定义bean绑定解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24