· 10 years ago · Sep 21, 2016, 05:04 AM
1import eventlet
2eventlet.monkey_patch()
3
4import itertools
5import pymysql
6import random
7from eventlet.green import time
8import greenlet
9
10def connect():
11 return pymysql.connect(user="scott", passwd="tiger", host="127.0.0.1", db="test")
12
13
14greenlet_id = itertools.count(1)
15
16
17def do_work(connections, conn_index):
18 our_id = next(greenlet_id)
19 conn = connections[conn_index]
20 while True:
21 try:
22 print("greenlet %d working..." % our_id)
23 cursor = conn.cursor()
24 for i in range(10):
25 cursor.execute(
26 "insert into stuff (data) values (%s)",
27 (("some_data_%f" % random.random()), )
28 )
29 cursor.close()
30 conn.commit()
31
32 cursor = conn.cursor()
33 cursor.execute("select sleep(%s)", (random.random(), ))
34 time.sleep(random.random())
35 if cursor.description is None:
36 raise Exception("cursor.description not supposed to be none")
37 cursor.fetchall()
38 cursor.close()
39 conn.rollback()
40 time.sleep(random.random())
41 except pymysql.Error as err:
42 print("error occurred, invalidating connection: %s" % err)
43 conn.rollback()
44 conn.close()
45 conn = connections[conn_index] = connect()
46 except Exception as err:
47 print("totally unexpected error occurred: %r" % err)
48 except greenlet.GreenletExit as ex:
49 print("exit exception: %r" % ex)
50 if ensure_greenlet_exit_handled:
51 conn.close()
52 conn = connections[conn_index] = connect()
53 break
54
55if __name__ == '__main__':
56 ensure_greenlet_exit_handled = False
57
58 num = 10
59
60 conn = connect()
61 cursor = conn.cursor()
62 cursor.execute("drop table if exists stuff")
63 cursor.execute(
64 "create table stuff(id integer primary key auto_increment, "
65 "data varchar(200))")
66 cursor.close()
67 conn.commit()
68
69 connections = [connect() for i in range(num)]
70
71 greenlets = [
72 eventlet.spawn(do_work, connections, idx)
73 for idx in range(num)]
74
75 while True:
76 for idx in range(num):
77 time.sleep(random.random())
78 print("kill...")
79 eventlet.greenthread.kill(greenlets[idx])
80 time.sleep(.5)
81 greenlets[idx] = eventlet.spawn(do_work, connections, idx)