




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、Redis And PythonPyCon India, 2011Sunil AroraRaising Hands.How many of you have used Redis before ?How many of you have got a laptop ?About MeI tweet atSunil Arora / _sunil_I work atShopSociallyI blog at Todays talkWhat is RedisHow it works and what you can do with itReal life use-casesReal life use-
2、casesSome hand-on with RedisRedis - Brief HistoryInitially written to improve performance of Web Analytics product LLOOGG out of his startupSalvatore Sanfilippoantirez Redis Brief HistoryReleased in March 2009 (Open Source, BSD licensed)VMWare hired Salvatore in March, 2010Then Pieter Noordhuis (key
3、 contributor) was hiredWhat is Redis ?Its between lot of stuff, so difficult to categorize it preciselyWhat is Redis ?I see Redis definitely more as a flexible tool that as a solution specialized to solve a specific problem: his mixed soul of cache, store, and messaging server shows this very well-S
4、alvatore SanfilippoPicture by herzogbr Redis is.Remote Data Structure ServerRedis is.Supports rich data types of computer science- Strings, Lists, Sets, Sorted Sets, Hashes.Rich sets of primitives (commands) to manipulate these types Predictive complexity measurementsA few fundamentalsWritten in C (
5、no external dependency)Uses memory as main storageUses disk for persistenceSingle ThreadedEvery command performs atomic execution PerformanceScreamingly fast performance50K read/write operations per seconds100K+ read/write ops per second on a regular EC2 instance Installation$ git clone $ cd redis$
6、make$ ./src/redis-server.$./src/redis-cliRedis PINGPONGPython LibrariesRedis-py - Python client libraryTxredisapi - An asynchronous Python client for the Redis database, based on Twisted.Redisco - ORM for redis along the lines Ohm for Rubyredis-pyThe most popular python client libraryAndy McCurdy (
7、)Github: $easy_install redis OR$pip install redisOptional$easy_install hiredis$pip install hiredisLets get started.$ cd redis$ ./src/redis-server. from redis import Redis redis_client = Redis() redis_client.keys() help(redis_client)Redis KeysNot binary safe.Should not contain space or newline charac
8、terA few rules about keys:Too long keys are not a good ideaToo short keys is also not a good idea“object-type:id:field” can be a nice idea, i.e. “user:1001:name”O(jiān)perations on KeysKEYSEXISTSDELEXPIREOBJECTPERSISTRANDOMKEYRENAMETYPETTLEXPIREATMOVELets play with keysredis_client.keys()redis_client.exis
9、ts(key)redis_client.delete(key)redis_client.type(key).Data StructuresStringsListsSetsSorted SetsHashesStringsSETGETMSETMGETSETEXGETSETSETNXINCRINCRBYDECRDECRBYStrings with redis client redis_client.set(key, value) redis_client.get(key) redis_client.delete(key)Fetch multiple keys at oncemget/msetredi
10、s_client.mset(key1: val1, key2: val2)redis_client.mget(key1, key2,.)ExpirationSet a value with expireredis_client.setex(key, value, 2) #key to expire in 2 secsredis_client.expire(key, 2)redis_client.get(key)NoneExpire SemanticsKey with expiry known as volatile keysWhenever a volatile key is modified
11、, its expiry is reset - To avoid inconsistency in following casesReplicationAppend Only LogUsesTo store transient states in your web applicationUsesWho is online?UsesRedis as LRU cache ( )Atomic Incrementshelp(redis_client.incr)help(redis_client.decr) redis_client.incr(counter, 1)1 redis_client.incr
12、(counter)2 redis_client.incr(counter)3UsesHigh Speed counters (views/clicks/votes/likes.)UsesAPI Rate LimitingUsesGenerating unique IDsListsOrdered list of binarysafe stringsDoubly linked listMemory footprint optimized for smaller listO(1) insertion/deletion at both endsLists - operationsLPUSHRPUSHL
13、SETLRANGELPOPBLPOPBRPOPBRPOPLPUSHLINSERTRPOPRPOPLPUSHLPUSHXRPUSHXUsesWeb apps are full of lists :)UsesCapped ListUsesReal time message QueueBackground Worker queues (Resque, Celery) UsesSocial Activity Streams or notificationsSetsAn unordered collection of distinct byte stringsNothing different from
14、 the data type in pythonSets - OperationsSADDSCARDSREMSISMEMBERSMEMBERSSPOPSRANDMEMBEROperations between SetsSMOVESUNIONSDIFFSINTERSets - OperationsSDIFFSTORESINTERSTORESUNIONSTORESets - UsesPicking random items from a set using SRANDMEMBEREx.Picking a random article from daily newsPick a random Ad
15、for servingPick a random option for A/BNote: Time complexity is O(1). Compare it with SQLs “order by Rand()”Sets - UsesTo model Relations in social graphEx.redis_client.sadd(friends:john, jenny, maria)redis_client.sadd(friends:ben, maria, kate)redis_client.sinter(friends:john, friends:ben)Relations
16、(friend/followers)Common followlist for A and Bsinter(users:A:follows, users:B:follows)Unique to B compared to Csdiff(users:B:follows, users:C:follows) Mutual relationship (friend as well as follower)sinter(users:B:followers, users:B:friends)Who does not follow me back ?sdiff(users:B:friends, users:
17、B:followers)Who am I not following back?sdiff(users:B:followers, user:B:friends)Which of my friends are online right now? SINTER online_people my_friendsWhich of my friends are online right now?RENAME online:fresh online:stale #every minuteSUNIONSTORE online:fresh online:stale#friend jack connectsSA
18、DD online:fresh jackSUNIONSTORE online online:fresh online:stale#who is online ?SINTER online friendsSorted SetsOrdered sets on the basis of scoreSorted SetsZADDZCARDZCOUNTZINCRBYZINTERSTOREZRANGEZRANGEBYSCOREZRANKZREMZREMRANGEBYRANKZREMRANGEBYSCOREZREVRANGEZREVRANGEBYSCOREZSCOREZUNIONSTORESorted Se
19、ts Use CaseTo build index on your datasetUses - Realtime Leaderboardszincrby(leaderboard, john, 2)zincrby(leaderboard, jack, 5)zincrby(leaderboard, kate, 1)zincrby(leaderboard, kate, 10).zrange(leaderboard, 0, -1, withscores = True)Uses - Realtime LeaderboardsMost download resourcesMost popular arti
20、cles on the websiteWeekly popular listMost downloaded stuff between date1 and date2. plete with Sored Sets HashesEquivalent to Python dictionary or Ruby hash or Java hashmapOperationshmset users:1 username: jim, score: 23hgetall users:1HincrbyUseful for storing structured datahmset user:1:preference
21、s flash_shown: yes, bgcolor: #fffExpire user:1:preferences Hmgetall user:1:preferences #returns entire dict Redis TransactionsUsing Multi/Watchp = redis_client.pipeline()p.lpush(a, 1)p.ltrim(a, 0, 100)p.executeLimitationSince commands are queued, Cant read valuesNo conditional executionIf not high write contention scenario, WATCH can be usedUse Redis Scripting to write your own primitiveDesigning with RedisData layout design on basis of QueryNo Query OptimizerManually build indexesDurabilitySnapshotting modeBinary dump every x secs or y opsAppen
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度房屋買賣合同小額貸款與房產(chǎn)評(píng)估機(jī)構(gòu)合作服務(wù)協(xié)議
- 2025年度高科技企業(yè)研發(fā)資金過橋借款協(xié)議
- 2025年度人工智能醫(yī)療診斷系統(tǒng)合同范本
- 體育體育課程改革與提升方案計(jì)劃
- 產(chǎn)品經(jīng)理工作回顧與市場需求分析計(jì)劃
- 心理科心理咨詢工作成果與發(fā)展計(jì)劃
- 建設(shè)學(xué)生藝術(shù)素養(yǎng)的美術(shù)教學(xué)工作方案計(jì)劃
- 時(shí)間管理技巧的深入探索計(jì)劃
- 加強(qiáng)醫(yī)院綠色低碳建設(shè)的實(shí)施計(jì)劃
- 2025年藥品批發(fā)零售項(xiàng)目建議書
- 《反電信網(wǎng)絡(luò)詐騙法》知識(shí)考試題庫150題(含答案)
- 2025年上海市各區(qū)初三一模語文試卷(打包16套無答案)
- 2025年度新能源汽車充電站運(yùn)營權(quán)轉(zhuǎn)讓合同樣本4篇
- 統(tǒng)編版五年級(jí)語文下冊(cè)1古詩三首《四時(shí)田園雜興(其三十一)》課件
- 《人工智能基礎(chǔ)》課件-AI的前世今生:她從哪里來
- 《學(xué)習(xí)共同體-走向深度學(xué)習(xí)》讀書分享
- 英語四線三格模板
- 大智慧指標(biāo)公式函數(shù)大全(完整可打印版)
- JIS G4305-2021 冷軋不銹鋼板材、薄板材和帶材
- 《中國近現(xiàn)代史綱要》上編教學(xué)案例分享
- 新加坡環(huán)境治理與保護(hù)
評(píng)論
0/150
提交評(píng)論