如果是一类问题.
所谓“类似队列的东西”,我的意思是支持以下操作:
可选操作如下:
如果可以以分布式方式(与队列交互的多个客户端)对队列执行以下操作,则是理想的:
queue = ...
queue.append( a )
queue.append( b )
queue.append( c )
print queue
"a b c"
queue.promote( b.id )
print queue
"b a c"
queue.demote( a.id )
"b c a"
x = queue.take()
print x
"b"
print queue
"c a"是否有特别适合此用例的数据存储?即使多个用户同时修改队列,队列也应该始终处于一致状态。
如果不是因为晋升/降级/调动的要求,就不会有什么问题了。
编辑:如果有Java和/或Python库来完成上面概述的任务,就会得到额外的分数。
解决方案的规模应该非常好。
发布于 2012-05-12 03:00:36
Python:“包括电池”
比起像RabbitMQ、Redis或关系数据库管理系统这样的数据存储,我认为python和一些库已经足够解决这个问题了。有些人可能会抱怨,这种自己动手的方法是重新发明轮子,但比起管理另一个数据存储,我更喜欢运行100行python代码。
实现优先级队列
您定义的操作:追加、获取、提升和降级,描述优先级队列。不幸的是,python没有内置的优先级队列数据类型。但是它确实有一个名为heapq的堆库,优先级队列通常被实现为堆。下面是满足您的需求的优先级队列的实现:
class PQueue:
"""
Implements a priority queue with append, take, promote, and demote
operations.
"""
def __init__(self):
"""
Initialize empty priority queue.
self.toll is max(priority) and max(rowid) in the queue
self.heap is the heap maintained for take command
self.rows is a mapping from rowid to items
self.pris is a mapping from priority to items
"""
self.toll = 0
self.heap = list()
self.rows = dict()
self.pris = dict()
def append(self, value):
"""
Append value to our priority queue.
The new value is added with lowest priority as an item. Items are
threeple lists consisting of [priority, rowid, value]. The rowid
is used by the promote/demote commands.
Returns the new rowid corresponding to the new item.
"""
self.toll += 1
item = [self.toll, self.toll, value]
self.heap.append(item)
self.rows[self.toll] = item
self.pris[self.toll] = item
return self.toll
def take(self):
"""
Take the highest priority item out of the queue.
Returns the value of the item.
"""
item = heapq.heappop(self.heap)
del self.pris[item[0]]
del self.rows[item[1]]
return item[2]
def promote(self, rowid):
"""
Promote an item in the queue.
The promoted item swaps position with the next highest item.
Returns the number of affected rows.
"""
if rowid not in self.rows: return 0
item = self.rows[rowid]
item_pri, item_row, item_val = item
next = item_pri - 1
if next in self.pris:
iota = self.pris[next]
iota_pri, iota_row, iota_val = iota
iota[1], iota[2] = item_row, item_val
item[1], item[2] = iota_row, iota_val
self.rows[item_row] = iota
self.rows[iota_row] = item
return 2
return 0demote命令与“促进”命令几乎相同,因此为了简洁起见,我将省略它。请注意,这仅取决于python的列表、dicts和heapq库。
服务我们的优先级队列
现在,对于PQueue数据类型,我们希望允许与实例进行分布式交互。这方面的一个很好的库是盖特姆。虽然well是比较新的,仍然是测试版,但它非常快速,测试也很好。使用gevent,我们可以很容易地设置一个监听localhost:4040的套接字服务器。以下是我的服务器代码:
pqueue = PQueue()
def pqueue_server(sock, addr):
text = sock.recv(1024)
cmds = text.split(' ')
if cmds[0] == 'append':
result = pqueue.append(cmds[1])
elif cmds[0] == 'take':
result = pqueue.take()
elif cmds[0] == 'promote':
result = pqueue.promote(int(cmds[1]))
elif cmds[0] == 'demote':
result = pqueue.demote(int(cmds[1]))
else:
result = ''
sock.sendall(str(result))
print 'Request:', text, '; Response:', str(result)
if args.listen:
server = StreamServer(('127.0.0.1', 4040), pqueue_server)
print 'Starting pqueue server on port 4040...'
server.serve_forever()在生产运行之前,您当然希望做一些更好的错误/缓冲区处理。但对快速原型来说效果很好。注意,这不需要对pqueue对象进行任何锁定。Gevent实际上并不并行运行代码,它只是给人留下了这样的印象。缺点是更多的核心不会有帮助,但好处是无锁代码。
不要误解我的意思,gevent SocketServer将同时处理多个请求。但它通过协同多任务处理在应答请求之间切换。这意味着你必须给出协同线的时间切片。虽然gevents套接字I/O函数的设计是为了产生结果,但我们的pqueue实现却不是。幸运的是,pqueue非常快地完成了它的任务。
也是一个客户
在原型化过程中,我发现有一个客户端也是有用的。编写客户端需要一些谷歌搜索,所以我也会分享这些代码:
if args.client:
while True:
msg = raw_input('> ')
sock = gsocket.socket(gsocket.AF_INET, gsocket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4040))
sock.sendall(msg)
text = sock.recv(1024)
sock.close()
print text要使用新的数据存储,首先启动服务器,然后启动客户端。在客户端提示下,您应该能够:
> append one
1
> append two
2
> append three
3
> promote 2
2
> promote 2
0
> take
two结垢极佳
考虑到您对数据存储的考虑,您似乎非常关注吞吐量和持久性。但是“规模非常好”并不能量化你的需求。因此,我决定用测试函数对上面的内容进行基准测试。下面是测试函数:
def test():
import time
import urllib2
import subprocess
import random
random = random.Random(0)
from progressbar import ProgressBar, Percentage, Bar, ETA
widgets = [Percentage(), Bar(), ETA()]
def make_name():
alphabet = 'abcdefghijklmnopqrstuvwxyz'
return ''.join(random.choice(alphabet)
for rpt in xrange(random.randrange(3, 20)))
def make_request(cmds):
sock = gsocket.socket(gsocket.AF_INET, gsocket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4040))
sock.sendall(cmds)
text = sock.recv(1024)
sock.close()
print 'Starting server and waiting 3 seconds.'
subprocess.call('start cmd.exe /c python.exe queue_thing_gevent.py -l',
shell=True)
time.sleep(3)
tests = []
def wrap_test(name, limit=10000):
def wrap(func):
def wrapped():
progress = ProgressBar(widgets=widgets)
for rpt in progress(xrange(limit)):
func()
secs = progress.seconds_elapsed
print '{0} {1} records in {2:.3f} s at {3:.3f} r/s'.format(
name, limit, secs, limit / secs)
tests.append(wrapped)
return wrapped
return wrap
def direct_append():
name = make_name()
pqueue.append(name)
count = 1000000
@wrap_test('Loaded', count)
def direct_append_test(): direct_append()
def append():
name = make_name()
make_request('append ' + name)
@wrap_test('Appended')
def append_test(): append()
...
print 'Running speed tests.'
for tst in tests: tst()基准结果
我对运行在笔记本电脑上的服务器进行了6次测试。我认为结果是非常好的。这是输出:
Starting server and waiting 3 seconds.
Running speed tests.
100%|############################################################|Time: 0:00:21
Loaded 1000000 records in 21.770 s at 45934.773 r/s
100%|############################################################|Time: 0:00:06
Appended 10000 records in 6.825 s at 1465.201 r/s
100%|############################################################|Time: 0:00:06
Promoted 10000 records in 6.270 s at 1594.896 r/s
100%|############################################################|Time: 0:00:05
Demoted 10000 records in 5.686 s at 1758.706 r/s
100%|############################################################|Time: 0:00:05
Took 10000 records in 5.950 s at 1680.672 r/s
100%|############################################################|Time: 0:00:07
Mixed load processed 10000 records in 7.410 s at 1349.528 r/s最后前沿:耐用性
最后,耐久性是唯一的问题,我没有完全原型。但我也不觉得有那么难。在优先级队列中,项的堆(列表)拥有将数据类型持久化到磁盘所需的所有信息。由于使用gevent,我们也可以以多处理的方式生成函数,所以我设想使用这样的函数:
def save_heap(heap, toll):
name = 'heap-{0}.txt'.format(toll)
with open(name, 'w') as temp:
for val in heap:
temp.write(str(val))
gevent.sleep(0)并将保存函数添加到优先级队列中:
def save(self):
heap_copy = tuple(self.heap)
toll = self.toll
gevent.spawn(save_heap, heap_copy, toll)现在,您可以每隔几分钟将数据存储分叉和写入磁盘的Redis模型复制一次。如果您需要更好的持久性,那么将上述功能与将命令记录到磁盘的系统结合起来。这些是Redis使用的AFP和RDB持久性方法。
发布于 2012-05-04 01:24:45
Redis支持列表和有序集:http://redis.io/topics/data-types#lists
它还支持事务和发布/订阅消息传递。所以,是的,我想说,这可以很容易地在红色。
更新:事实上,大约80%的用户已经做了很多次:http://www.google.co.uk/search?q=python+redis+queue
其中几个点击可以升级以添加您想要的内容。您必须使用事务来实现提升/降级操作。
可以在服务器端使用lua来创建该功能,而不是在客户端代码中使用它。或者,您可以在服务器上创建一个围绕redis的薄包装器,实现您想要的操作。
发布于 2012-05-04 01:43:13
Websphere几乎可以完成所有这些工作。
提升/降级几乎是可能的,方法是从队列中删除消息并以更高/较低的优先级将其重新加载,或者使用"CORRELID“作为序列号。
https://stackoverflow.com/questions/10404921
复制相似问题