Whakataki
Me titiro tatou ki tetahi tauira o te putunga matua/wariu, penei i te memcache. He mea hanga noa - ka penapena nga raraunga ki roto i te mahara, i roto i te anga mahere hashmap. Ka uru atu ma te turanga tcp. I roto i te Python, ko te hashmap he korero auau. Mo te uru ka whakamahia e matou te zeromq.
whakatikatikanga
Hei whakauru i tenei kete ki te debian/ubuntu, tomo noa ki te papatohu
sudo apt-get install libzmq-dev
sudo pip install zmq
Waehere
Me tuhi he karaehe hei mahi tahi me to tatou tūmau:
Ko te momo turanga zmq e whakamahia ana ko REQ(REQuest, request), ka tukuna he tono me te tatari mo te whakautu.
Hei rokiroki me te tuku i tetahi momo raraunga i runga i te whatunga, ka whakamahia e matou te kōwae pikara paerewa. Ko te mahi "kawa" he tuple o nga uara e toru: (whakahau, matua, raraunga)
import zmq
import pickle
class SuperCacher:
def __init__(self):
context = zmq.Context()
self.socket = context.socket(zmq.REQ)
self.socket.connect('tcp://127.0.0.1:43000')
def get(self, key):
self.socket.send(pickle.dumps(('get', key, None)))
return pickle.loads(self.socket.recv())
def set(self, key, data):
self.socket.send(pickle.dumps(('set', key, data)))
return self.socket.recv() == b'ok'
Whakamahia
keteroki = SuperCacher()
cache.set('kī', 'uara')
cache.get('key')
Hei mahi kainga, whakapai ake i te whakatinanatanga ma te taapiri i te kaha ki te tautuhi i tetahi wahitau/tauranga i te wa e hanga ana he tauira o te karaehe.
Inaianei me tuhi te tūmau ake.
I tenei wa ka whakamahia te turanga REP(REPly, response) - kei te tatari matou mo te tono, ka tukuna he whakautu. Ka wetewetehia te tono me te whakautu me te 'ok' i roto i te take o te tuhi, me te raraunga ranei / Karekau mo te panui.
import pickle
import json
import zmq
def run_daemon():
memory = {}
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind('tcp://127.0.0.1:43000')
while True:
try:
command, key, data = pickle.loads(socket.recv())
if command == 'set':
memory[key] = data
socket.send(b'ok')
elif command == 'get':
result = memory.get(key, None)
socket.send(pickle.dumps(result))
except Exception as e:
print(e)
if __name__ == '__main__':
run_daemon()
Hei whakamatautau tahi i nga mea katoa, ka tiimata te tūmau me te whakahau
python daemon.py
I te ripa e whai ake nei, whakarewahia te python ki te aratau tauwhitiwhiti.
>>> from lib import SuperCacher
>>> cache=SuperCacher()
>>> cache.set('key', 'value')
True
>>> cache.get('key')
'value'
Aue, te mahi! Inaianei ka taea e koe te tuhi i roto i to reanga "whakawhanaketanga o te rokiroki uara-matua ma te whakamahi i te kawa zmq"
Source: will.com