转载自centos中文站http://www.centoscn.com/python/2013/0817/1324.html
1.安装redis
1.1、准备部分:
什么是redis?
Redis是REmote DIctionary Server的缩写。一个非关系型数据库
为什么要用redis?
1, 因为redis快,Redis is pretty fast!, 110000 SETs/second, 81000 GETs/second
2, 省去了复杂的SQL。
3, 可以省去memcache了。
1.2、下载,解压和编译:
$ wget http://redis.googlecode.com/files/redis-2.6.13.tar.gz $ tar xzf redis-2.6.13.tar.gz $ cd redis-2.6.13 $ make
为什么没用标准的Linux安装三板斧呢?官方维基是这样说的:Redis can run just fine without a configuration file (when executed without a config file a standard configuration is used). With thedefault configuration Redis will log to the standard output so you can check what happens. Later, you canchange the default settings.
1.3、运行redis
编译的可执行文件在src目录中,使用以下命令运行Redis:
$ src/redis-server
1.4、连接Redis
你可以用内置客户端连接Redis:
$ src/redis-cli redis> set foo bar OK redis> get foo "bar"
1.5、配置redis
在运行redis前,我们要配置一下。redis的配置文件在你的安装目录里。名为:redis.conf。
简单说几点redis.conf:
redis默认不是用守护进程的,如果需要更改,把daemonize no改成daemonize yes。(测试的时候可以不改,看看打印信息。)
如果对redis默认6379端口不爽的,可以更改port 6379
如果想把数据文件放到一个指定文件夹,更改dir /opt/data/
默认是dir ./ 也就是默认放到安装目录下。
连接超时时间,timeout 300,没什么改头……
dir 是数据文件路径。默认在安装目录下。
*下面的配置二选一,详见本文注释部分2。
###### SNAPSHOTTING ######内存快照方式:
默认的内存快照策略是,
在900秒(15分钟)内,至少有1次数据变更;
或者300秒内,有至少10次数据变更;
或者60秒内,有至少1000次数据变更;时间+数据变更次数,共同影响内存快照的出现。
###### APPEND ONLY MODE ###### AOF方式
appendfsync everysec 每秒同步。这里可以注释掉,打开下面的选项appendfsync no
其余的配置,conf里面的注释写的挺清楚,我就不多废话了。大家看着自己配就行了。
注释:
▲redis的默认端口号是6379,(据redis的作者antirez的博文说,6379在是手机按键上MERZ对应的号码,而MERZ取自意大利歌女Alessia Merz的名字。而MERZ长期以来被antirez及其朋友当作愚蠢的代名词。)
▲Redis有两种存储方式,默认是snapshot方式,实现方法是定时将内存的快照(snapshot)持久化到硬盘,这种方法缺点是持久化之 后如果出现crash则会丢失一段数据。因此在完美主义者的推动下作者增加了aof方式。aof即append only mode,在写入内存数据的同时将操作命令保存到日志文件。
参考:
nosql发烧友集散地:
http://blog.nosqlfan.com
redis认识的几个误区:
http://blog.nosqlfan.com/html/868.html
借鉴:
http://shopscor.javaeye.com/blog/792817
2.安装redis-py
运行
打开Python解释器:
>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0) #如果设置了密码,就加上password=密码
>>> r.set('foo', 'bar') #或者写成 r['foo'] = 'bar'
True
>>> r.get('foo')
'bar'
>>> r.delete('foo')
True
>>> r.dbsize() #库里有多少key,多少条数据
0
>>> r['test']='OK!'
>>> r.save() #强行把数据库保存到硬盘。保存时阻塞
True
--------------------------------
>>> r.flushdb() #删除当前数据库的所有数据
True
>>> a = r.get('chang')
>>> a # 因为是Noen对象,什么也不显示!
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> r.exists('chang') #看是否存在这个键值
False
>>> r.keys() # 列出所有键值。(这时候已经存了4个了)
['aaa', 'test', 'bbb', 'key1']
附注A:
来看一下redis.Redis的 init() 函数定义:
__init__(self, host='localhost', port=6379, db=0, password=None, socket_timeout=None, connection_pool=None, charset='utf-
8', errors='strict', decode_responses=False, unix_socket_path=None)
最新的redis 2.6.0加入了连接池,具体用法可以看作者博客。
附注B:
其他命令API,请参照redis-Python作者的博客,写的挺清楚了:
https://github.com/andymccurdy/redis-py