Elton's Blog

Author Archive

在Mac OSX下安装和使用GO语言

by Elton on 2010年08月13日, under Agile Web Development, Mac

Go语言是Google新推出的结合了动态语言和静态语言优势的一个新兴的语言。下面介绍一下如何在Mac系统下安装和使用这个语言。

设置环境变量

$GOROOT
GO语言的根目录,通常是$HOME/go,当然也可以是任何其他目录。

$GOOS 和 $GOARCH
标明GO语言所在的系统和处理器类型。$GOOS可以是linux, freebsd, darwin (Mac OS X 10.5 or 10.6)和 nacl (Native Client, an incomplete port)。$GOARCH可以是amd64 (64-bit x86, the most mature port), 386 (32-bit x86), arm (32-bit ARM, an incomplete port)。

你可以在你的shell profile中设置这些变量,我是放在了~/.bash_profile里了。

  1. export GOROOT=$HOME/go
  2. export GOARCH=amd64
  3. export GOOS=darwin
  4. export PATH=$PATH:$HOME/bin

其中, $HOME/bin是GO默认的可执行文件的目录,加入到path中方便使用go的各种命令。

再执行

  1. source ~/.bash_profile

使最新的配置文件生效。

获得源文件

如果你的系统中没有安装Mercurial(没有安装它,你就无法使用hg命令),那么使用这个命令来安装它:

  1.  
  2. $ sudo easy_install mercurial
  3.  

然后使用下面的命令,还获得GO语言的源文件

  1.  
  2. $ hg clone -r release https://go.googlecode.com/hg/ $GOROOT
  3.  

安装GO语言

  1.  
  2. $ cd $GOROOT/src
  3. $ ./all.bash
  4.  

如果一切正常,你应该可以在最后看到类似的结果:

  1.  
  2. cd ../test
  3. N known bugs; 0 unexpected bugs
  4.  

撰写第一个Hello,World

  1.  
  2. $ cat >hello.go <<EOF
  3. package main
  4.  
  5. import "fmt"
  6.  
  7. func main() {
  8.         fmt.Printf("hello, world\n")
  9. }
  10. EOF
  11.  
  12. $ 6g hello.go
  13. $ 6l hello.6
  14. $ ./6.out
  15. hello, world
  16. $
  17.  

日后更新

Go是一个发展中的语言,它的版本会经常进行更新,可以使用以下命令,保持GO语言是最新版本的

  1.  
  2. $ cd $GOROOT/src
  3. $ hg pull
  4. $ hg update release
  5. $ ./all.bash
  6.  

Go的官方网站是:http://golang.org

9 Comments :, , , more...

额尔古纳逐梦之旅

by Elton on 2010年08月13日, under Photography

经过了6天的跋涉,终于完成了此次内蒙古的行程。一路走过确实很辛苦,但是也很快乐。体会到了人生的真正含义,感受到了祖国的大好河山。

从上海出发,沿途经过江苏、安徽、河北、天津、辽宁、吉林、黑龙江,最后到达内蒙古。共计8天时间,全程逾6千公里。 具体路线如下:

蓝色为去程,红色为返程。

D1: 上海 – 唐山 1,235 公里
D2:唐山 – 哈尔滨 1,094 公里
D3:哈大高速(哈尔滨-大庆)-301国道(大庆-齐齐哈尔-阿荣旗(那吉)- 博克图 – 牙克石-呼伦贝尔草原-海拉尔),818公里
D4:海拉尔 – 金帐汗 – 额尔古纳 – 恩和 – 室韦 287公里
D5:室韦 – 黑山头 – 满州里330公里(走边防公路(摄影小路)全程草原风光摄影爱好者的天堂 黑山头界河游坐船饱览两岸风光住满洲里欣赏满洲里夜景)
D6:203省道(满洲里 – 达来 – 新巴尔虎右旗 – 甘珠尔 – 新巴尔虎左旗 – 罕达盖 – 伊尔施 – 阿尔山市)- 111国道 – 乌兰浩特
D7: 111国道(乌兰浩特 – 科尔沁右旗中旗 – 通辽)- 大连
D8:大连 – 葫芦岛滚装轮渡 – 上海

美丽的额尔古纳
额尔古纳

边陲小镇 – 室韦
室韦

山顶的卫星接收站
额尔古纳

室韦 – 满洲里的边境公路
边境公路

边境公路

美丽的中俄界河 额尔古纳河
额尔古纳河

漂亮的满洲里
满洲里

阿尔山国家地质公园
阿尔山

阿尔山

更多图片在我的相册里。

3 Comments :, , , , , , , more...

URL设计准则

by Elton on 2010年08月10日, under Web

URL 设计是 Web 设计中常被忽视的东西,事实上 URL 非常重要,这不仅是一个网页唯一的路径,还涉及到你的站点是否干净,友好。本文讲述 URL 这个司空见惯的 Web 元素中包含的大量不应为忽视的知识,准则与最佳实践。需要注意的是 W3C 建议使用 URI 取代 URL 一说。
关于 URL 的一些准则
首先是与 URL 有关的一些准则。

一个 URL 必须唯一地,永久地代表一个在线对象

URL 的最基本的使命是唯一地代表 Internet 上的一个对象,URL 必须和 Internet 上的对象一对一匹配。然而现实中,这很难实现,我们经常可以通过多个 URL 到达同一个页面,比如, http://mysite.com/product/tv 和 http://mysite.com/product?name=tv,这种情形在现代 CMS 中更是比比皆是,针对这个问题,SEO moz 有一篇很好的文章,讲到了如何使用 Canonical URL 机制解决站点中的重复 URL 问题。
URL 应该是永久的,这就要求你在站点上线前就非常严谨地规划 URL。如果有一天,你不得不更改 URL,一定使用 HTTP 301 机制,告诉浏览器和搜索引擎,你的那个 URL 所代表的对象,已经搬迁到新地址,这个机制可以保证你旧地址所获得 PR 不会被清零。

尽可能用户友好

这是 URL 设计的根本,你的 URL 应该为最终用户而设计。保持 URL 友好的一个好办法是在保证可读性的同时让它尽可能短。比如 /about 就好过 /about-acme-corp-page,当然,保持简短不能牺牲可读性, /13d2 一类的地址短则短矣,但并不友好。如果要在 Twitter, Facebook 一类的社会媒体网络分享你的 URL,可以使用 Bit.ly 一类的网址缩短工具,但这种工具产生的缩短 URL 并不友好,在 WordPress 一类的 CMS 中,可以使用 PrettyLink Pro 或 Short URL plugin 一类的可控制的地址缩短插件。

URL 的设计切忌使用一些对用户来说没有意义的内容,比如数据库的 ID 号, /products/23 这样的 URL 地址对用户是极不友好的,应当使用 /products/ballpoint-pen 一类的地址。

保持一致性

站点内的所有 URL 必须保持一致的格式和结构,这样可以为用户带来信任感,如果你必须更改 URL 格式和结构,需要使用 HTTP 301 机制。

可预测的 URL

这也是 URL 一致性的一个表现,如果你的 URL 拥有很好的一致性,用户可以根据 URL 猜测别的内容的 URL,假如 /events/2010/01 指向 2010 年 1 月份的日程内容,那
/events/2009/01 应当指向 2009 年 1 月的日程。
/events/2010 应当指向 2010 年全年的日程。
/events/2010/01/21 应当指向2010年1月21日的日程。

URL中的关键词

URL 中应该包含本页重点内容的关键词,比如 /posts/2010/07/02/trip-best-buy-memory-cards 一类的 URL 本身就是对页面内容的反应。在 URL 包含重点内容关键词,也可以提高 SEO 性能。SEO 的一个很重要的原则就是,在 URL 地址中包含内容关键词。
关于 URL 的技术细节
下面说的是有关 URL 的一些技术细节。

URL 不应包含 .html, aspx, cfm 一类的后缀

这类信息对最终用户是没有意义的,却占了额外的空间,一个例外是 .atom, .rss, .json 一类的特殊地址,这类地址是有特别的意义的。译者注:在某些虚拟主机式 Web 服务器,这种做法未必现实。

URL 不应包含 WWW 部分

WWW 部分并不包含任何意义,是一个额外的负担,不友好。可以使用 HTTP 301 机制,将 www.domain.com 定向到 domain.com 。

URL 的格式

URL 的格式如下:
domain.com/[key information]/[name]/?[modifiers]
Key information 部分一般代表信息的类型或类别。Modifiers 部分则属于查询字符串范畴,它不应当代表数据结构,应当代表数据的修饰。Key information 部分应当尽可能简短,同时应当表现出一种层级关系,比如 http://domain.com/posts/servers/nginx-ubuntu-10.04,或 http://domain.com/news/tech/2007/11/05/google-announces-android。
Google News 对新闻源有一个有趣的要求,Google 要求新闻源页面的 URL 中必须包含至少 3 位唯一的数字,因为他们会忽略年份数字,因此,应该使用一个5位或5位以上的数字。另外,也应该提供 Google News 站点地图 。如果你想向 Google 提供新闻,必须按这样的结构提供 URL,当然保持一致性,可以预测性也是必需的。

使用小写字符

URL 中所有字符都应使用小写,这更容易阅读。

URL 中包含的行为元素

URL 查询字符串中可能包含一些表示行为的元素,比如 show, delete, edit 等。非破坏性的行为可以体现在 URL 中,破坏性的行为应该使用 POST 。

使用 URL 友好字符

在 URL 中体现网页标题的时候,往往会用到一些特殊字符,应当把它们转换为 URL 友好字符:
全部大写字符换成小写
诸如 é 一类的字符应转换成对应的 e
空格使用短划线代替
诸如 !, @, #, $, %, ^, &, * 一类的字符应该使用短划线代替
双短划线应该使用单短划线代替
另外,没有必要的话,避免使用 %20 一类的 URL 逃逸符。

更多观点

Chris Shiflett 建议,可以使用一些类似句子的 URL,如:
chriscoyier.net/authored/digging-into-wordpress/
chriscoyier.net/has-worked-for/chatman-design/
chriscoyier.net/likes/trailer-park-boys
jacobwg.com/thinks/this-post/is/basically-done

译者补充:URL 的长度上限
URL 的最大长度是多少?W3C 的 HTTP 协议 并没有限定,然而,在实际应用中,经过试验,不同浏览器和 Web 服务器有不同的约定:
IE 的 URL 长度上限是 2083 字节,其中纯路径部分不能超过 2048 字节。
Firefox 浏览器的地址栏中超过 65536 字符后就不再显示。
Safari 浏览器一致测试到 80000 字符还工作得好好的。
Opera 浏览器测试到 190000 字符的时候,还正常工作。
Web 服务器:
Apache Web 服务器在接收到大约 4000 字符长的 URL 时候产生 413 Entity Too Large” 错误。
IIS 默认接收的最大 URL 是 16384 字符。

2 Comments : more...

iPhone/Mac Objective-C内存管理教程和原理剖析(四)系统自动创建新的autorelease pool

by Elton on 2010年07月29日, under Mac, iPhone

四 系统自动创建新的autorelease pool
在生成新的Run Loop的时候,系统会自动创建新的autorelease pool(非常感谢网友hhyytt和neogui的提醒)。注意,此处不同于xcode在新建项目时自动生成的代码中加入的autorelease pool,xcode生成的代码可以被删除,但系统自动创建的新的autorelease pool是无法删除的(对于无Garbage Collection的环境来说)。Objective-C没有给出实现代码,官方文档也没有说明,但我们可以通过小程序来证明。
在这个小程序中,我们先生成了一个autorelease pool,然后生成一个autorelease的ClassA的实例,再在一个新的run loop中生成一个autorelease的ClassB的对象(注意,我们并没有手动在新run loop中生成autorelease pool)。精简的示例代码如下,详细代码请见附件中的memman-run-loop-with-pool.m。

  1.  
  2. int main(int argc, char**argv)
  3. {
  4.          NSLog(@"create an autorelasePool\n");
  5.          NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
  6.  
  7.          NSLog(@"create an instance of ClassA and autorelease\n");
  8.          ClassA *obj1 = [[[ClassA alloc] init] autorelease];
  9.          NSDate *now = [[NSDate alloc] init];
  10.          NSTimer *timer = [[NSTimer alloc] initWithFireDate:now
  11.                    interval:0.0
  12.                    target:obj1
  13.                    selector:@selector(createClassB)
  14.                    userInfo:nil
  15.                    repeats:NO];
  16.          NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  17.          [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
  18.          [timer release];
  19.          [now release];
  20.          [runLoop run]; //在新loop中调用一函数,生成ClassB的autorelease实例
  21.  
  22.          NSLog(@"releasing autorelasePool\n");
  23.          [pool release];
  24.          NSLog(@"autorelasePool is released\n");
  25.          return 0;
  26. }
  27.  

输出如下:

  1.  
  2. create an autorelasePool
  3. create an instance of ClassA and autorelease
  4. create an instance of ClassB and autorelease
  5. ClassB destroyed
  6. releasing autorelasePool
  7. ClassA destroyed
  8. autorelasePool is released
  9.  

注意在我们销毁autorelease pool之前,ClassB的autorelease实例就已经被销毁了。
有人可能会说,这并不能说明新的run loop自动生成了一个新的autorelease pool,说不定还只是用了老的autorelease pool,只不过后来drain了一次而已。我们可以在main函数中不生成autorelease pool。精简的示例代码如下,详细代码请见附件中的memman-run-loop-without-pool.m。

  1.  
  2. int main(int argc, char**argv)
  3. {
  4.          NSLog(@"No autorelasePool created\n");
  5.  
  6.          NSLog(@"create an instance of ClassA\n");
  7.          ClassA *obj1 = [[ClassA alloc] init];
  8.          NSDate *now = [[NSDate alloc] init];
  9.          NSTimer *timer = [[NSTimer alloc] initWithFireDate:now
  10.                    interval:0.0
  11.                    target:obj1
  12.                    selector:@selector(createClassB)
  13.                    userInfo:nil
  14.                    repeats:NO];
  15.          NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  16.          [runLoop addTimer:timer forMode:NSDefaultRunLoopMode];
  17.          [timer release];
  18.          [now release];
  19.          [runLoop run]; //在新loop中调用一函数,生成ClassB的autorelease实例
  20.          NSLog(@"Manually release the instance of ClassA\n");
  21.          [obj1 release];
  22.  
  23.          return 0;
  24. }
  25.  

输出如下:

  1.  
  2. No autorelasePool created
  3. create an instance of ClassA
  4. create an instance of ClassB and autorelease
  5. ClassB destroyed
  6. Manually release the instance of ClassA
  7. ClassA destroyed
  8.  

我们可以看出来,我们并没有创建任何autorelease pool,可是ClassB的实例依然被自动销毁了,这说明新的run loop自动创建了一个autorelease pool,这个pool在新的run loop结束的时候会销毁自己(并自动release所包含的对象)。

补充说明
在研究retain count的时候,我不建议用NSString。因为在下面的语句中,

  1.  
  2. NSString *str1 = @”constant string”;
  3.  

str1的retain count是个很大的数字。Objective-C对常量字符串做了特殊处理。
当然,如果你这样创建NSString,得到的retain count依然为1

  1.  
  2. NSString *str2 = [NSString stringWithFormat:@”123];
  3.  

摘自:http://www.cnblogs.com/VinceYuan

4 Comments :, , , more...

iPhone/Mac Objective-C内存管理教程和原理剖析(三)@property (retain)和@synthesize的默认实现

by Elton on 2010年07月29日, under Mac, iPhone

三 @property (retain)和@synthesize的默认实现
在这里解释一下@property (retain) ClassB* objB;和@synthesize objB;背后到底发生了什么(retain property的默认实现)。property实际上是getter和setter,针对有retain参数的property,背后的实现如下(请参考附件中的memman-getter-setter.m,你会发现,结果和memman-property.m一样):

  1.  
  2. @interface ClassA : NSObject
  3. {
  4.          ClassB *objB;
  5. }
  6.  
  7. -(ClassB *) getObjB;
  8. -(void) setObjB:(ClassB *) value;
  9. @end
  10.  
  11. @implementation ClassA
  12. -(ClassB*) getObjB
  13. {
  14.          return objB;
  15. }
  16.  
  17. -(void) setObjB:(ClassB*) value
  18. {
  19.          if (objB != value)
  20.          {
  21.                    [objB release];
  22.                    objB = [value retain];
  23.          }
  24. }
  25.  

在setObjB中,如果新设定的值和原值不同的话,必须要把原值对象release一次,这样才能保证retain count是正确的。
由于我们在class内部retain了一次(虽然是默认实现的),所以我们要在dealloc方法中release这个成员变量。

  1.  
  2. -(void) dealloc
  3. {
  4.          [objB release];
  5.          [super dealloc];
  6. }
  7.  

摘自:http://www.cnblogs.com/VinceYuan

Leave a Comment :, , , more...

iPhone/Mac Objective-C内存管理教程和原理剖析(二)口诀与范式

by Elton on 2010年07月29日, under Mac, iPhone

二 口诀与范式
1 口诀。
1.1 谁创建,谁释放(类似于“谁污染,谁治理”)。如果你通过alloc、new或copy来创建一个对象,那么你必须调用release或autorelease。换句话说,不是你创建的,就不用你去释放。
例如,你在一个函数中alloc生成了一个对象,且这个对象只在这个函数中被使用,那么你必须在这个函数中调用release或autorelease。如果你在一个class的某个方法中alloc一个成员对象,且没有调用autorelease,那么你需要在这个类的dealloc方法中调用release;如果调用了autorelease,那么在dealloc方法中什么都不需要做。
1.2 除了alloc、new或copy之外的方法创建的对象都被声明了autorelease。
1.3 谁retain,谁release。只要你调用了retain,无论这个对象是如何生成的,你都要调用release。有时候你的代码中明明没有retain,可是系统会在默认实现中加入retain。不知道为什么苹果公司的文档没有强调这个非常重要的一点,请参考范式2.7和第三章。
2 范式。
范式就是模板,就是依葫芦画瓢。由于不同人有不同的理解和习惯,我总结的范式不一定适合所有人,但我能保证照着这样做不会出问题。
2.1 创建一个对象。

  1.  
  2. ClassA *obj1 = [[ClassA alloc] init];
  3.  

2.2 创建一个autorelease的对象。

  1.  
  2. ClassA *obj1 = [[[ClassA alloc] init] autorelease];
  3.  

2.3 Release一个对象后,立即把指针清空。(顺便说一句,release一个空指针是合法的,但不会发生任何事情)

  1.  
  2. [obj1 release];
  3. obj1 = nil;
  4.  

2.4 指针赋值给另一个指针。

  1.  
  2. ClassA *obj2 = obj1;
  3. [obj2 retain];
  4. //do something
  5. [obj2 release];
  6. obj2 = nil;
  7.  

2.5 在一个函数中创建并返回对象,需要把这个对象设置为autorelease

  1.  
  2. ClassA *Func1()
  3. {
  4.   ClassA *obj = [[[ClassA alloc]init]autorelease];
  5.   return obj;
  6. }
  7.  

2.6 在子类的dealloc方法中调用基类的dealloc方法

  1.  
  2. -(void) dealloc
  3. {
  4.          …
  5.          [super dealloc];
  6. }
  7.  

2.7 在一个class中创建和使用property。
2.7.1 声明一个成员变量。

  1.  
  2. ClassB *objB;
  3.  

2.7.2 声明property,加上retain参数。

  1.  
  2. @property (retain) ClassB* objB;
  3.  

2.7.3 定义property。(property的默认实现请看第三章)

  1.  
  2. @synthesize objB;
  3.  

2.7.4 除了dealloc方法以外,始终用.操作符的方式来调用property。
self.objB 或者objA.objB
2.7.5 在dealloc方法中release这个成员变量。

  1.  
  2. [objB release];
  3.  

示例代码如下(详细代码请参考附件中的memman-property.m,你需要特别留意对象是在何时被销毁的。):

  1.  
  2. @interface ClassA : NSObject
  3. {
  4.          ClassB* objB;
  5. }
  6.  
  7. @property (retain) ClassB* objB;
  8. @end
  9.  
  10. @implementation ClassA
  11. @synthesize objB;
  12. -(void) dealloc
  13. {
  14.          [objB release];
  15.          [super dealloc];
  16. }
  17. @end
  18.  

2.7.6 给这个property赋值时,有手动release和autorelease两种方式。

  1.  
  2. void funcNoAutorelease()
  3. {
  4.          ClassB *objB1 = [[ClassB alloc]init];
  5.          ClassA *objA = [[ClassA alloc]init];
  6.          objA.objB = objB1;
  7.          [objB1 release];
  8.          [objA release];
  9. }
  10.  
  11. void funcAutorelease()
  12. {
  13.          ClassB *objB1 = [[[ClassB alloc]init] autorelease];
  14.          ClassA *objA = [[[ClassA alloc]init] autorelease];
  15.          objA.objB = objB1;
  16. }
  17.  

摘自: http://www.cnblogs.com/VinceYuan/

2 Comments :, , , more...

iPhone/Mac Objective-C内存管理教程和原理剖析(一)基本原理

by Elton on 2010年07月29日, under Mac, iPhone

前言
初学objectice-C的朋友都有一个困惑,总觉得对objective-C的内存管理机制琢磨不透,程序经常内存泄漏或莫名其妙的崩溃。我在这里总结了自己对objective-C内存管理机制的研究成果和经验,写了这么一个由浅入深的教程。希望对大家有所帮助,也欢迎大家一起探讨。

此文涉及的内存管理是针对于继承于NSObject的Class。
一 基本原理
Objective-C的内存管理机制与.Net/Java那种全自动的垃圾回收机制是不同的,它本质上还是C语言中的手动管理方式,只不过稍微加了一些自动方法。
1 Objective-C的对象生成于堆之上,生成之后,需要一个指针来指向它。

  1.  
  2. ClassA *obj1 = [[ClassA alloc] init];
  3.  

2 Objective-C的对象在使用完成之后不会自动销毁,需要执行dealloc来释放空间(销毁),否则内存泄露。

  1.  
  2. [obj1 dealloc];
  3.  

这带来了一个问题。下面代码中obj2是否需要调用dealloc?

  1.  
  2. ClassA *obj1 = [[ClassA alloc] init];
  3. ClassA *obj2 = obj1;
  4. [obj1 hello]; //输出hello
  5. [obj1 dealloc];
  6. [obj2 hello]; //能够执行这一行和下一行吗?
  7. [obj2 dealloc];
  8.  

不能,因为obj1和obj2只是指针,它们指向同一个对象,[obj1 dealloc]已经销毁这个对象了,不能再调用[obj2 hello]和[obj2 dealloc]。obj2实际上是个无效指针。
如何避免无效指针?请看下一条。

3 Objective-C采用了引用计数(ref count或者retain count)。对象的内部保存一个数字,表示被引用的次数。例如,某个对象被两个指针所指向(引用)那么它的retain count为2。需要销毁对象的时候,不直接调用dealloc,而是调用release。release会让retain count减1,只有retain count等于0,系统才会调用dealloc真正销毁这个对象。

  1.  
  2. ClassA *obj1 = [[ClassA alloc] init]; //对象生成时,retain count = 1
  3. [obj1 release]; //release使retain count减1,retain count = 0,dealloc自动被调用,对象被销毁
  4.  

我们回头看看刚刚那个无效指针的问题,把dealloc改成release解决了吗?

  1.  
  2. ClassA *obj1 = [[ClassA alloc] init]; //retain count = 1
  3. ClassA *obj2 = obj1; //retain count = 1
  4. [obj1 hello]; //输出hello
  5. [obj1 release]; //retain count = 0,对象被销毁
  6. [obj2 hello];
  7. [obj2 release];
  8.  

[obj1 release]之后,obj2依然是个无效指针。问题依然没有解决。解决方法见下一条。

4 Objective-C指针赋值时,retain count不会自动增加,需要手动retain。

  1.  
  2. ClassA *obj1 = [[ClassA alloc] init]; //retain count = 1
  3. ClassA *obj2 = obj1; //retain count = 1
  4. [obj2 retain]; //retain count = 2
  5. [obj1 hello]; //输出hello
  6. [obj1 release]; //retain count = 2 – 1 = 1
  7. [obj2 hello]; //输出hello
  8. [obj2 release]; //retain count = 0,对象被销毁
  9.  

问题解决!注意,如果没有调用[obj2 release],这个对象的retain count始终为1,不会被销毁,内存泄露。(1-4可以参考附件中的示例程序memman-no-pool.m)
这样的确不会内存泄露,但似乎有点麻烦,有没有简单点的方法?见下一条。

5 Objective-C中引入了autorelease pool(自动释放对象池),在遵守一些规则的情况下,可以自动释放对象。(autorelease pool依然不是.Net/Java那种全自动的垃圾回收机制)
5.1 新生成的对象,只要调用autorelease就行了,无需再调用release!

  1.  
  2. ClassA *obj1 = [[[ClassA alloc] init] autorelease]; //retain count = 1 但无需调用release
  3.  

5.2 对于存在指针赋值的情况,代码与前面类似。

  1.  
  2. ClassA *obj1 = [[[ClassA alloc] init] autorelease]; //retain count = 1
  3. ClassA *obj2 = obj1; //retain count = 1
  4. [obj2 retain]; //retain count = 2
  5. [obj1 hello]; //输出hello
  6. //对于obj1,无需调用(实际上不能调用)release
  7. [obj2 hello]; //输出hello
  8. [obj2 release]; //retain count = 2-1 = 1
  9.  

细心的读者肯定能发现这个对象没有被销毁,何时销毁呢?谁去销毁它?(可以参考附件中的示例程序memman-with-pool.m)请看下一条。

6 autorelease pool原理剖析。(其实很简单的,一定要坚持看下去,否则还是不能理解Objective-C的内存管理机制。)
6.1 autorelease pool不是天生的,需要手动创立。只不过在新建一个iphone项目时,xcode会自动帮你写好。autorelease pool的真名是NSAutoreleasePool。

  1.  
  2. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  3.  

6.2 NSAutoreleasePool内部包含一个数组(NSMutableArray),用来保存声明为autorelease的所有对象。如果一个对象声明为autorelease,系统所做的工作就是把这个对象加入到这个数组中去。

  1.  
  2. ClassA *obj1 = [[[ClassA alloc] init] autorelease]; //retain count = 1,把此对象加入autorelease pool中
  3.  

6.3 NSAutoreleasePool自身在销毁的时候,会遍历一遍这个数组,release数组中的每个成员。如果此时数组中成员的retain count为1,那么release之后,retain count为0,对象正式被销毁。如果此时数组中成员的retain count大于1,那么release之后,retain count大于0,此对象依然没有被销毁,内存泄露。
6.4 默认只有一个autorelease pool,通常类似于下面这个例子。

  1.  
  2. int main (int argc, const char *argv[])
  3. {
  4. pool = [[NSAutoreleasePool alloc] init];
  5.  
  6. // do something
  7.  
  8. [pool release];
  9. return (0);
  10. } // main
  11.  

所有标记为autorelease的对象都只有在这个pool销毁时才被销毁。如果你有大量的对象标记为autorelease,这显然不能很好的利用内存,在iphone这种内存受限的程序中是很容易造成内存不足的。例如:

  1.  
  2. int main (int argc, const char *argv[])
  3. {
  4. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  5. int i, j;
  6. for (i = 0; i < 100; i++ )
  7. {
  8.  for (j = 0; j < 100000; j++ )
  9.     [NSString stringWithFormat:@"1234567890"];//产生的对象是autorelease的。
  10. }
  11. [pool release];
  12. return (0);
  13. } // main
  14.  

(可以参考附件中的示例程序memman-many-objs-one-pool.m,运行时通过监控工具可以发现使用的内存在急剧增加,直到pool销毁时才被释放)你需要考虑下一条。

7 Objective-C程序中可以嵌套创建多个autorelease pool。在需要大量创建局部变量的时候,可以创建内嵌的autorelease pool来及时释放内存。(感谢网友hhyytt和neogui的提醒,某些情况下,系统会自动创建autorelease pool, 请参见第四章)

  1.  
  2. int main (int argc, const char *argv[])
  3. {
  4. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  5. int i, j;
  6. for (i = 0; i < 100; i++ )
  7. {
  8.  NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
  9.  for (j = 0; j < 100000; j++ )
  10.     [NSString stringWithFormat:@"1234567890"];//产生的对象是autorelease的。
  11.  [loopPool release];
  12. }
  13. [pool release];
  14. return (0);
  15. } // main
  16.  

(可以参考附件中的示例程序memman-many-objs-many-pools.m,占用内存的变化极小)

转载自:http://www.cnblogs.com/VinceYuan

Leave a Comment :, , , more...

通过URL Rewrite来设置JBoss的301跳转

by Elton on 2010年07月28日, under Java, Linux

Introduction

The rewrite valve implements URL rewrite functionnality in a way that is very similar to mod_rewrite from Apache HTTP Server.

Configuration

The rewrite valve is configured as a regular valve, by adding the following to server.xml as child of an Engine or Host element (or inside a context.xml file):

  1. <Valve className="org.jboss.web.rewrite.RewriteValve" />

The valve will then use a rewrite.properties file containing the rewrite directives, located according to the container it is assocaited to:

If associated with an engine, it should be placed in a folder named [engine_name] placed either in the classloader, or in the conf folder of the current JBoss profile
If associated with a host, it should be placed in a folder named [engine_name]/[host_name] placed either in the classloader, or in the conf folder of the current JBoss profile
If associated with a context, it should be placed in the WEB-INF folder of the web application
Directives

The rewrite.properties file contains a list of directives which closely resemble the directives used by mod_rewrite, in particular the central RewriteRule and RewriteCond directives.

Note: This section is a modified version of the mod_rewrite documentation, which is Copyright 1995-2006 The Apache Software Foundation, and licensed under the under the Apache License, Version 2.0.

RewriteCond

Syntax: RewriteCond TestString CondPattern

The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following rule is then only used if both the current state of the URI matches its pattern, and if these conditions are met.

TestString is a string which can contain the following expanded constructs in addition to plain text:

RewriteRule backreferences: These are backreferences of the form $N (0 <= N <= 9), which provide access to the grouped parts (in parentheses) of the pattern, from the RewriteRule which is subject to the current set of RewriteCond conditions..
RewriteCond backreferences: These are backreferences of the form %N (1 <= N <= 9), which provide access to the grouped parts (again, in parentheses) of the pattern, from the last matched RewriteCond in the current set of conditions.
RewriteMap expansions: These are expansions of the form ${mapname:key|default}. See the documentation for RewriteMap for more details.
Server-Variables: These are variables of the form %{ NAME_OF_VARIABLE } where NAME_OF_VARIABLE can be a string taken from the following list:
HTTP headers: connection & request:
HTTP_USER_AGENT
HTTP_REFERER
HTTP_COOKIE
HTTP_FORWARDED
HTTP_HOST
HTTP_PROXY_CONNECTION
HTTP_ACCEPT
REMOTE_ADDR
REMOTE_HOST
REMOTE_PORT
REMOTE_USER
REMOTE_IDENT
REQUEST_METHOD
SCRIPT_FILENAME
REQUEST_PATH
CONTEXT_PATH
SERVLET_PATH
PATH_INFO
QUERY_STRING
AUTH_TYPE
server internals: date and time: specials:
DOCUMENT_ROOT
SERVER_NAME
SERVER_ADDR
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
TIME_YEAR
TIME_MON
TIME_DAY
TIME_HOUR
TIME_MIN
TIME_SEC
TIME_WDAY
TIME
THE_REQUEST
REQUEST_URI
REQUEST_FILENAME
HTTPS
These variables all correspond to the similarly named HTTP MIME-headers and Servlet API methods. Most are documented elsewhere in the Manual or in the CGI specification. Those that are special to the rewrite valve include those below.

REQUEST_PATH
Corresponds to the full path that is used for mapping.
CONTEXT_PATH
Corresponds to the path of the mapped context.
SERVLET_PATH
Corresponds to the servlet path.
THE_REQUEST
The full HTTP request line sent by the browser to the server (e.g., "GET /index.html HTTP/1.1"). This does not include any additional headers sent by the browser.
REQUEST_URI
The resource requested in the HTTP request line. (In the example above, this would be "/index.html".)
REQUEST_FILENAME
The full local filesystem path to the file or script matching the request.
HTTPS
Will contain the text "on" if the connection is using SSL/TLS, or "off" otherwise.
Other things you should be aware of:

The variables SCRIPT_FILENAME and REQUEST_FILENAME contain the same value - the value of the filename field of the internal request_rec structure of the Apache server. The first name is the commonly known CGI variable name while the second is the appropriate counterpart of REQUEST_URI (which contains the value of the uri field of request_rec).
%{ENV:variable}, where variable can be any Java system property, is also available.
%{SSL:variable}, where variable is the name of an SSL environment variable, are not implemented yet. Example: %{SSL:SSL_CIPHER_USEKEYSIZE} may expand to 128.
%{HTTP:header}, where header can be any HTTP MIME-header name, can always be used to obtain the value of a header sent in the HTTP request. Example: %{HTTP:Proxy-Connection} is the value of the HTTP header ``Proxy-Connection:''.
CondPattern is the condition pattern, a regular expression which is applied to the current instance of the TestString. TestString is first evaluated, before being matched against CondPattern.

Remember: CondPattern is a perl compatible regular expression with some additions:

You can prefix the pattern string with a '!' character (exclamation mark) to specify a non-matching pattern.
There are some special variants of CondPatterns. Instead of real regular expression strings you can also use one of the following:
' Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString lexicographically precedes CondPattern.
'>CondPattern’ (lexicographically follows)
Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString lexicographically follows CondPattern.
‘=CondPattern’ (lexicographically equal)
Treats the CondPattern as a plain string and compares it lexicographically to TestString. True if TestString is lexicographically equal to CondPattern (the two strings are exactly equal, character for character). If CondPattern is “” (two quotation marks) this compares TestString to the empty string.
‘-d’ (is directory)
Treats the TestString as a pathname and tests whether or not it exists, and is a directory.
‘-f’ (is regular file)
Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.
‘-s’ (is regular file, with size)
Treats the TestString as a pathname and tests whether or not it exists, and is a regular file with size greater than zero.
. All of these tests can also be prefixed by an exclamation mark (‘!’) to negate their meaning.
You can also set special flags for CondPattern by appending [flags] as the third argument to the RewriteCond directive, where flags is a comma-separated list of any of the following flags:
‘nocase|NC’ (no case)
This makes the test case-insensitive – differences between ‘A-Z’ and ‘a-z’ are ignored, both in the expanded TestString and the CondPattern. This flag is effective only for comparisons between TestString and CondPattern. It has no effect on filesystem and subrequest checks.
‘ornext|OR’ (or next condition)
Use this to combine rule conditions with a local OR instead of the implicit AND. Typical example:

  1.  
  2. RewriteCond %{REMOTE_HOST}  ^host1.*  [OR]
  3. RewriteCond %{REMOTE_HOST}  ^host2.*  [OR]
  4. RewriteCond %{REMOTE_HOST}  ^host3.*
  5.  

RewriteRule …some special stuff for any of these hosts…
Without this flag you would have to write the condition/rule pair three times.
Example:

To rewrite the Homepage of a site according to the “User-Agent:” header of the request, you can use the following:

  1.  
  2. RewriteCond  %{HTTP_USER_AGENT}  ^Mozilla.*
  3. RewriteRule  ^/$                 /homepage.max.html  [L]
  4.  
  5. RewriteCond  %{HTTP_USER_AGENT}  ^Lynx.*
  6. RewriteRule  ^/$                 /homepage.min.html  [L]
  7.  
  8. RewriteRule  ^/$                 /homepage.std.html  [L]
  9.  

Explanation: If you use a browser which identifies itself as ‘Mozilla’ (including Netscape Navigator, Mozilla etc), then you get the max homepage (which could include frames, or other special features). If you use the Lynx browser (which is terminal-based), then you get the min homepage (which could be a version designed for easy, text-only browsing). If neither of these conditions apply (you use any other browser, or your browser identifies itself as something non-standard), you get the std (standard) homepage.

RewriteMap

Syntax: RewriteMap name rewriteMapClassName optionalParameters

The maps are implemented using an interface that users must implement. Its class name is org.jboss.web.rewrite.RewriteMap, and its code is:

  1.  
  2. package org.jboss.web.rewrite;
  3.  
  4. public interface RewriteMap {
  5.     public String setParameters(String params);
  6.     public String lookup(String key);
  7. }
  8.  

RewriteRule

Syntax: RewriteRule Pattern Substitution

The RewriteRule directive is the real rewriting workhorse. The directive can occur more than once, with each instance defining a single rewrite rule. The order in which these rules are defined is important – this is the order in which they will be applied at run-time.

Pattern is a perl compatible regular expression, which is applied to the current URL. “Current” means the value of the URL when this rule is applied. This may not be the originally requested URL, which may already have matched a previous rule, and have been altered.

Some hints on the syntax of regular expressions:

Text:
. Any single character
[chars] Character class: Any character of the class “chars”
[^chars] Character class: Not a character of the class “chars”
text1|text2 Alternative: text1 or text2

Quantifiers:
? 0 or 1 occurrences of the preceding text
* 0 or N occurrences of the preceding text (N > 0)
+ 1 or N occurrences of the preceding text (N > 1)

Grouping:
(text) Grouping of text
(used either to set the borders of an alternative as above, or
to make backreferences, where the Nth group can
be referred to on the RHS of a RewriteRule as $N)

Anchors:
^ Start-of-line anchor
$ End-of-line anchor

Escaping:
\char escape the given char
(for instance, to specify the chars “.[]()” etc.)
For more information about regular expressions, have a look at the perl regular expression manpage (“perldoc perlre”). If you are interested in more detailed information about regular expressions and their variants (POSIX regex etc.) the following book is dedicated to this topic:

Mastering Regular Expressions, 2nd Edition
Jeffrey E.F. Friedl
O’Reilly & Associates, Inc. 2002
ISBN 0-596-00289-0
In the rules, the NOT character (‘!’) is also available as a possible pattern prefix. This enables you to negate a pattern; to say, for instance: “if the current URL does NOT match this pattern”. This can be used for exceptional cases, where it is easier to match the negative pattern, or as a last default rule.

Note: When using the NOT character to negate a pattern, you cannot include grouped wildcard parts in that pattern. This is because, when the pattern does NOT match (ie, the negation matches), there are no contents for the groups. Thus, if negated patterns are used, you cannot use $N in the substitution string!

The substitution of a rewrite rule is the string which is substituted for (or replaces) the original URL which Pattern matched. In addition to plain text, it can include

back-references ($N) to the RewriteRule pattern
back-references (%N) to the last matched RewriteCond pattern
server-variables as in rule condition test-strings (%{VARNAME})
mapping-function calls (${mapname:key|default})
Back-references are identifiers of the form $N (N=0..9), which will be replaced by the contents of the Nth group of the matched Pattern. The server-variables are the same as for the TestString of a RewriteCond directive. The mapping-functions come from the RewriteMap directive and are explained there. These three types of variables are expanded in the order above.

As already mentioned, all rewrite rules are applied to the Substitution (in the order in which they are defined in the config file). The URL is completely replaced by the Substitution and the rewriting process continues until all rules have been applied, or it is explicitly terminated by a flag.

There is a special substitution string named ‘-’ which means: NO substitution! This is useful in providing rewriting rules which only match URLs but do not substitute anything for them. It is commonly used in conjunction with the C (chain) flag, in order to apply more than one pattern before substitution occurs.

Additionally you can set special flags for Substitution by appending [flags] as the third argument to the RewriteRule directive. Flags is a comma-separated list of any of the following flags:

‘chain|C’ (chained with next rule)
This flag chains the current rule with the next rule (which itself can be chained with the following rule, and so on). This has the following effect: if a rule matches, then processing continues as usual – the flag has no effect. If the rule does not match, then all following chained rules are skipped. For instance, it can be used to remove the “.www” part, inside a per-directory rule set, when you let an external redirect happen (where the “.www” part should not occur!).
‘cookie|CO=NAME:VAL:domain[:lifetime[:path]]’ (set cookie)
This sets a cookie in the client’s browser. The cookie’s name is specified by NAME and the value is VAL. The domain field is the domain of the cookie, such as ‘.apache.org’, the optional lifetime is the lifetime of the cookie in minutes, and the optional path is the path of the cookie
‘env|E=VAR:VAL’ (set environment variable)
This forces an environment variable named VAR to be set to the value VAL, where VAL can contain regexp backreferences ($N and %N) which will be expanded. You can use this flag more than once, to set more than one variable. The variables can later be dereferenced in many situations, most commonly from within XSSI (via ) or CGI ($ENV{‘VAR’}). You can also dereference the variable in a later RewriteCond pattern, using %{ENV:VAR}. Use this to strip information from URLs, while maintaining a record of that information.
‘forbidden|F’ (force URL to be forbidden)
This forces the current URL to be forbidden – it immediately sends back a HTTP response of 403 (FORBIDDEN). Use this flag in conjunction with appropriate RewriteConds to conditionally block some URLs.
‘gone|G’ (force URL to be gone)
This forces the current URL to be gone – it immediately sends back a HTTP response of 410 (GONE). Use this flag to mark pages which no longer exist as gone.
‘host|H=Host’ (apply rewriting to host)
Rather that rewrite the URL, the virtual host will be rewritten.
‘last|L’ (last rule)
Stop the rewriting process here and don’t apply any more rewrite rules. This corresponds to the Perl last command or the break command in C. Use this flag to prevent the currently rewritten URL from being rewritten further by following rules. For example, use it to rewrite the root-path URL (‘/’) to a real one, e.g., ‘/e/www/’.
‘next|N’ (next round)
Re-run the rewriting process (starting again with the first rewriting rule). This time, the URL to match is no longer the original URL, but rather the URL returned by the last rewriting rule. This corresponds to the Perl next command or the continue command in C. Use this flag to restart the rewriting process – to immediately go to the top of the loop.
Be careful not to create an infinite loop!
‘nocase|NC’ (no case)
This makes the Pattern case-insensitive, ignoring difference between ‘A-Z’ and ‘a-z’ when Pattern is matched against the current URL.
‘noescape|NE’ (no URI escaping of output)
This flag prevents the rewrite valve from applying the usual URI escaping rules to the result of a rewrite. Ordinarily, special characters (such as ‘%’, ‘$’, ‘;’, and so on) will be escaped into their hexcode equivalents (‘%25′, ‘%24′, and ‘%3B’, respectively); this flag prevents this from happening. This allows percent symbols to appear in the output, as in RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE] which would turn ‘/foo/zed’ into a safe request for ‘/bar?arg=P1=zed’.
‘qsappend|QSA’ (query string append)
This flag forces the rewrite engine to append a query string part of the substitution string to the existing string, instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.
‘redirect|R [=code]‘ (force redirect)
Prefix Substitution with http://thishost[:thisport]/ (which makes the new URL a URI) to force a external redirection. If no code is given, a HTTP response of 302 (MOVED TEMPORARILY) will be returned. If you want to use other response codes in the range 300-400, simply specify the appropriate number or use one of the following symbolic names: temp (default), permanent, seeother. Use this for rules to canonicalize the URL and return it to the client – to translate “/~” into “/u/”, or to always append a slash to /u/user, etc.
Note: When you use this flag, make sure that the substitution field is a valid URL! Otherwise, you will be redirecting to an invalid location. Remember that this flag on its own will only prepend http://thishost[:thisport]/ to the URL, and rewriting will continue. Usually, you will want to stop rewriting at this point, and redirect immediately. To stop rewriting, you should add the ‘L’ flag.
‘skip|S=num’ (skip next rule(s))
This flag forces the rewriting engine to skip the next num rules in sequence, if the current rule matches. Use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes skip=N, where N is the number of rules in the else-clause. (This is not the same as the ‘chain|C’ flag!)
‘type|T=MIME-type’ (force MIME type)
Force the MIME-type of the target file to be MIME-type. This can be used to set up the content-type based on some conditions. For example, the following snippet allows .php files to be displayed by mod_php if they are called with the .phps extension: RewriteRule ^(.+\.php)s$ $1 [T=application/x-httpd-php-source]

参考:http://www.jboss.org/file-access/default/members/jbossweb/freezone/modules/rewrite/index.html

34 Comments :, , more...

MySQL Query Cache

by Elton on 2010年07月5日, under Database

顾名思义,MySQL Query Cache 就是用来缓存和 Query 相关的数据的。具体来说,Query Cache 缓存了我们客户端提交给 MySQL 的 SELECT 语句以及该语句的结果集。大概来讲,就是将 SELECT 语句和语句的结果做了一个 HASH 映射关系然后保存在一定的内存区域中。

在大部分的 MySQL 分发版本中,Query Cache 功能默认都是打开的,我们可以通过调整 MySQL Server 的参数选项打开该功能。主要由以下5个参数构成:

query_cache_limit:允许 Cache 的单条 Query 结果集的最大容量,默认是1MB,超过此参数设置的 Query 结果集将不会被 Cache
query_cache_min_res_unit:设置 Query Cache 中每次分配内存的最小空间大小,也就是每个 Query 的 Cache 最小占用的内存空间大小
query_cache_size:设置 Query Cache 所使用的内存大小,默认值为0,大小必须是1024的整数倍,如果不是整数倍,MySQL 会自动调整降低最小量以达到1024的倍数
query_cache_type:控制 Query Cache 功能的开关,可以设置为0(OFF),1(ON)和2(DEMAND)三种,意义分别如下:
0(OFF):关闭 Query Cache 功能,任何情况下都不会使用 Query Cache
1(ON):开启 Query Cache 功能,但是当 SELECT 语句中使用的 SQL_NO_CACHE 提示后,将不使用Query Cache
2(DEMAND):开启 Query Cache 功能,但是只有当 SELECT 语句中使用了 SQL_CACHE 提示后,才使用 Query Cache
query_cache_wlock_invalidate:控制当有写锁定发生在表上的时刻是否先失效该表相关的 Query Cache,如果设置为 1(TRUE),则在写锁定的同时将失效该表相关的所有 Query Cache,如果设置为0(FALSE)则在锁定时刻仍然允许读取该表相关的 Query Cache。
Query Cache 如何处理子查询的?
这是我遇到的最为常见的一个问题。其实 Query Cache 是以客户端请求提交的 Query 为对象来处理的,只要客户端请求的是一个 Query,无论这个 Query 是一个简单的单表查询还是多表 Join,亦或者是带有子查询的复杂 SQL,都被当作成一个 Query,不会被分拆成多个 Query 来进行 Cache。所以,存在子查询的复杂 Query 也只会产生一个Cache对象,子查询不会产生单独的Cache内容。UNION[ALL] 类型的语句也同样如此。

Query Cache 是以 block 的方式存储的数据块吗?
不是,Query Cache 中缓存的内容仅仅只包含该 Query 所需要的结果数据,是结果集。当然,并不仅仅只是结果数据,还包含与该结果相关的其他信息,比如产生该 Cache 的客户端连接的字符集,数据的字符集,客户端连接的 Default Database等。

Query Cache 为什么效率会非常高,即使所有数据都可以 Cache 进内存的情况下,有些时候也不如使用 Query Cache 的效率高?
Query Cache 的查找,是在 MySQL 接受到客户端请求后在对 Query 进行权限验证之后,SQL 解析之前。也就是说,当 MySQL 接受到客户端的SQL后,仅仅只需要对其进行相应的权限验证后就会通过 Query Cache 来查找结果,甚至都不需要经过 Optimizer 模块进行执行计划的分析优化,更不许要发生任何存储引擎的交互,减少了大量的磁盘 IO 和 CPU 运算,所以效率非常高。

客户端提交的 SQL 语句大小写对 Query Cache 有影响吗?
有,由于 Query Cache 在内存中是以 HASH 结构来进行映射,HASH 算法基础就是组成 SQL 语句的字符,所以必须要整个 SQL 语句在字符级别完全一致,才能在 Query Cache 中命中,即使多一个空格也不行。

一个 SQL 语句在 Query Cache 中的内容,在什么情况下会失效?
为了保证 Query Cache 中的内容与是实际数据绝对一致,当表中的数据有任何变化,包括新增,修改,删除等,都会使所有引用到该表的 SQL 的 Query Cache 失效。

为什么我的系统在开启了 Query Cache 之后整体性能反而下降了?
当开启了 Query Cache 之后,尤其是当我们的 query_cache_type 参数设置为 1 以后,MySQL 会对每个 SELECT 语句都进行 Query Cache 查找,查找操作虽然比较简单,但仍然也是要消耗一些 CPU 运算资源的。而由于 Query Cache 的失效机制的特性,可能由于表上的数据变化比较频繁,大量的 Query Cache 频繁的被失效,所以 Query Cache 的命中率就可能比较低下。所以有些场景下,Query Cache 不仅不能提高效率,反而可能造成负面影响。

如何确认一个系统的 Query Cache 的运行是否健康,命中率如何,设置量是否足够?
MySQL 提供了一系列的 Global Status 来记录 Query Cache 的当前状态,具体如下:

Qcache_free_blocks:目前还处于空闲状态的 Query Cache 中内存 Block 数目
Qcache_free_memory:目前还处于空闲状态的 Query Cache 内存总量
Qcache_hits:Query Cache 命中次数
Qcache_inserts:向 Query Cache 中插入新的 Query Cache 的次数,也就是没有命中的次数
Qcache_lowmem_prunes:当 Query Cache 内存容量不够,需要从中删除老的 Query Cache 以给新的 Cache 对象使用的次数
Qcache_not_cached:没有被 Cache 的 SQL 数,包括无法被 Cache 的 SQL 以及由于 query_cache_type 设置的不会被 Cache 的 SQL
Qcache_queries_in_cache:目前在 Query Cache 中的 SQL 数量
Qcache_total_blocks:Query Cache 中总的 Block 数量
可以根据这几个状态计算出 Cache 命中率,计算出 Query Cache 大小设置是否足够,总的来说,我个人不建议将 Query Cache 的大小设置超过256MB,这也是业界比较常用的做法。

MySQL Cluster 是否可以使用 Query Cache?
其实在我们的生产环境中也没有使用 MySQL Cluster,所以我也没有在 MySQL Cluster 环境中使用 Query Cache 的实际经验,只是 MySQL 文档中说明确实可以在 MySQL Cluster 中使用 Query Cache。从 MySQL Cluster 的原理来分析,也觉得应该可以使用,毕竟 SQL 节点和数据节点比较独立,各司其职,只是 Cache 的失效机制会要稍微复杂一点。

引自:http://www.javaeye.com/news/16744-mysql-query-cache-summary

2 Comments :, , more...

iPhone 3GS升级iOS4.0并越狱

by Elton on 2010年07月4日, under iPhone

手上有一部港行的iPhone 3GS,虽然是41周前的,但是因为之前用了Spirit,所以无法直接使用自制固件了。

今天发现一个Cydia上的软件,可以解决这个问题。

前提就是您必须在iPhone 3GS的(旧的bootrom)和Spirit 越狱3.1.3

*打开cydia,并添加源 – > http://repo.woowiz.net
*现在搜索 – > Spirit2Pwn。
*安装Spirit2Pwn和重新启动设备。

现在,Spirits越狱的机器可以接受任何自制4.0固件了.

Leave a Comment :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...