使用Python操作Azure Service Bus队列删除消息时锁无效报错求助
Fixing "The lock supplied is invalid" Error When Deleting Azure Service Bus Queue Messages in Python
Hey there, let's break down why you're seeing that frustrating lock error and how to fix it.
First, let's unpack what that error message means:
- Either the lock on your message expired (Azure Service Bus holds a lock on messages received in PeekLock mode for a set timeout, usually 30-60 seconds by default)
- Or the message was already deleted or processed elsewhere
- Or you're passing incorrect sequence number/lock token values to the delete method
Looking at your code, there are a couple of clear issues triggering this:
- You’re using hardcoded sequence numbers and lock tokens (like
5andef4e2189-bfef-42ac-ba09-7fd20287f6a9) — these values are tied to a specific message, and once that message’s lock expires or it’s deleted, they become useless. - You have a line where you pass literal strings
'SequenceNumber'and'LockToken'as parameters, which is invalid — the method expects actual values pulled from the received message.
Here's the corrected approach:
You need to capture the sequence number and lock token directly from the message you receive, then use those values to delete the message before the lock expires.
from azure.servicebus.control_client import ServiceBusService, Message, Topic, Rule, DEFAULT_RULE_NAME # Initialize your Service Bus client key_name = '###############' # Replace with your SharedAccessKeyName from Azure Portal key_value = '####################' # Replace with your SharedAccessKey service_namespace = '###########' # Replace with your service namespace sbs = ServiceBusService(service_namespace, shared_access_key_name=key_name, shared_access_key_value=key_value) # Receive a message (default is PeekLock mode, which holds a lock on the message) msg = sbs.receive_queue_message('taskqueue') # Only attempt deletion if we actually received a message if msg: # Use the message's own sequence number and lock token to delete it sbs.delete_queue_message('taskqueue', msg.sequence_number, msg.lock_token) print("Message deleted successfully!") else: print("No messages available in the queue.")
Additional Tips to Avoid This Error:
- Extend the lock if needed: If your message processing takes longer than the default lock timeout, call
msg.renew_lock()periodically to keep the lock alive. - Skip PeekLock entirely (if appropriate): If you don’t need to handle message failures (i.e., you want to delete the message immediately when receiving it), use
peek_lock=Falsein the receive call:# This receives and deletes the message in one step, no need to call delete_queue_message msg = sbs.receive_queue_message('taskqueue', peek_lock=False) - Never reuse lock tokens/sequence numbers: Each message has unique values, and locks are one-time use — once expired or used, they can’t be reused.
内容的提问来源于stack exchange,提问作者Moon
相关产品推荐
相关产品推荐

