import
SocketServer,sys
from
threading
import
Thread
import
socket
from
hash_ring
import
HashRing
redis_servers
=
[
'127.0.0.1:6480'
,
'127.0.0.1:6481'
,
'127.0.0.1:6482'
]
ring
=
HashRing(redis_servers)
class
service(SocketServer.BaseRequestHandler):
def
handle(
self
):
data
=
'dummy'
print
"Client connected with "
,
self
.client_address
while
len
(data):
data
=
self
.request.recv(
1024
)
if
data:
key
=
(data.split(
"\n"
))[
4
]
server
=
ring.get_node(key)
s
=
socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(((server.split(
":"
))[
0
],
int
((server.split(
":"
))[
1
])))
s.sendall(data)
r_data
=
s.recv(
1024
)
print
server
self
.request.send(r_data)
print
"Client exited"
self
.request.close()
class
ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
try
:
t
=
ThreadedTCPServer(('',
6379
), service)
t.serve_forever()
except
KeyboardInterrupt:
sys.exit(
1
)