Cách xử lý lỗi kết nối trong python

Chương này sẽ thảo luận về cách xử lý các lỗi xảy ra khi làm việc với thư viện yêu cầu Http. Luôn luôn là một thực hành tốt để quản lý lỗi cho tất cả các trường hợp có thể xảy ra

Ngoại lệ lỗi

Mô-đun yêu cầu cung cấp các loại ngoại lệ lỗi sau -

ConnectionError - Điều này sẽ được nâng lên, nếu có bất kỳ lỗi kết nối nào. Ví dụ mạng bị lỗi, lỗi DNS thì thư viện Request sẽ tăng ngoại lệ ConnectionError

Phản ứng. raise_for_status[] − Dựa trên mã trạng thái i. e. 401, 404, nó sẽ tăng HTTPError cho url được yêu cầu

HTTPError - Lỗi này sẽ xuất hiện khi có phản hồi không hợp lệ đối với yêu cầu được thực hiện

Hết thời gian - Lỗi tăng lên khi hết thời gian cho URL được yêu cầu

TooManyRedirects - Nếu vượt quá giới hạn cho các chuyển hướng tối đa thì nó sẽ gây ra lỗi TooManyRedirects

cơ sở dữ liệu. Tên cơ sở dữ liệu để ghi dữ liệu vào. Nó sẽ tạo cơ sở dữ liệu nếu cổng không tồn tại. Một số cho biết cổng mà influxdb đang lắng nghe series_name. Tên của chuỗi/bảng để ghi dữ liệu vào polling_interval. khoảng thời gian bỏ phiếu cho các phép đo tính bằng giây [mặc định. 1] lưu_duration. khoảng thời gian để giữ lại các phép đo cho các giá trị hợp lệ là 1h, 90m, 12h, 7d và 4w. vỡ nợ. thẻ 1d. Một hoặc nhiều thẻ để áp dụng cho dữ liệu. Sau đó, chúng có thể được sử dụng để nhóm hoặc chọn chuỗi thời gian Ví dụ. --machine my_machine --cluster kerb01 """ logger = _logger[] logger. info['Đang cố gắng kết nối với {} trên cổng {} là {}'. định dạng [ip_or_url, cổng, tên người dùng]] hãy thử. client = InfluxDBClient[ip_or_url, port, username, password] phản hồi = client. ping[] ngoại trừ Lỗi kết nối. tiều phu. cảnh báo ['Không thể kết nối với InfluxDB. Số liệu GPU KHÔNG được ghi lại'] raise MetricsRecordingFailed[] logger. thông tin ['Đã kết nối. phiên bản {}'. format[response]] _switch_to_database[client, database] logger. info['Thời lượng lưu giữ phép đo {}'. định dạng[thời lượng lưu giữ]] _set_retention_policy[máy khách, cơ sở dữ liệu, thời lượng lưu giữ] to_db = soạn thảo[_create_influxdb_writer[máy khách, thẻ=thẻ], _gpu_to_influxdb_format[series_name]] trình ghi nhật ký. info['Bắt đầu đăng nhập. '] return start_pusshing_measurements_to[to_db, polling_interval=polling_interval]

Trong mọi hệ thống phân tán, độ bền của ứng dụng của bạn phụ thuộc vào khả năng phục hồi nhanh chóng từ các sự kiện không mong muốn. Ứng dụng khách AMPS cung cấp các khối xây dựng cần thiết để đảm bảo ứng dụng của bạn có thể phục hồi từ các loại lỗi và sự kiện đặc biệt có thể xảy ra khi sử dụng AMPS

ngoại lệ

Nói chung, khi xảy ra lỗi ngăn không cho thao tác thành công, AMPS sẽ đưa ra một ngoại lệ. Các trường hợp ngoại lệ AMPS thường bắt nguồn từ AMPS.AMPSException, vì vậy bằng cách bắt AMPSException, bạn sẽ chắc chắn bắt được bất cứ thứ gì mà AMPS ném ra, chẳng hạn

def read_and_evaluate[client]:
    # read a new payload from the user
    payload = input["Please enter a message"]

    # write a new message to AMPS
    if payload:
        try:
            client.publish[
                "UserMessage",
                "{ \"message\" : \"%s\"  }" % payload
            ]
        except AMPS.AMPSException as e:
            sys.stderr.write["An AMPS exception" + "occurred: %s" % str[e]]

Ví dụ 5. 1. Bắt ngoại lệ AMPS

Trong ví dụ này, nếu xảy ra lỗi, chương trình sẽ ghi lỗi vào stderr và lệnh

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
0 không thành công. Tuy nhiên,
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
1 vẫn có thể sử dụng để tiếp tục xuất bản và đăng ký. Khi xảy ra lỗi, ngoại lệ được ghi vào bàn điều khiển. Như với hầu hết các ngoại lệ Python,
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
2 sẽ chuyển đổi ngoại lệ thành một chuỗi bao gồm thông báo mô tả

Các loại ngoại lệ AMPS khác nhau dựa trên bản chất của lỗi xảy ra. Trong chương trình của bạn, nếu bạn muốn xử lý một số loại lỗi khác với những lỗi khác, bạn có thể xử lý lớp con thích hợp của AMPSException để phát hiện những lỗi cụ thể đó và thực hiện điều gì đó khác biệt

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream

Ví dụ 5. 2. Xử lý các lớp con AMPSException

Các loại ngoại lệ

Mỗi phương thức trong AMPS ghi lại các loại ngoại lệ được đưa ra từ nó. Để tham khảo, chứa danh sách tất cả các loại ngoại lệ bạn có thể gặp phải khi sử dụng AMPS, thời điểm chúng xảy ra và ý nghĩa của chúng

Xử lý ngoại lệ và xử lý tin nhắn không đồng bộ

Khi sử dụng xử lý thông báo không đồng bộ, các ngoại lệ được ném từ trình xử lý thông báo sẽ được ứng dụng khách AMPS Python hấp thụ theo mặc định. Ứng dụng khách AMPS Python cho phép bạn đăng ký một trình xử lý ngoại lệ để phát hiện và phản hồi các ngoại lệ này. Khi một trình nghe ngoại lệ được đăng ký, AMPS sẽ gọi trình nghe ngoại lệ có ngoại lệ. Thấy

để biết chi tiết

Xử lý ngắt kết nối

Mọi hệ thống phân tán sẽ thỉnh thoảng bị ngắt kết nối giữa một hoặc nhiều nút. Độ tin cậy của toàn bộ hệ thống phụ thuộc vào khả năng của ứng dụng trong việc phát hiện và khôi phục hiệu quả sau những lần ngắt kết nối này. Sử dụng khả năng xử lý ngắt kết nối của ứng dụng khách AMPS Python, bạn có thể xây dựng các ứng dụng mạnh mẽ có khả năng phục hồi khi gặp lỗi kết nối và ngắt kết nối giả. Để có thêm độ tin cậy, bạn cũng có thể sử dụng ứng dụng khách có tính sẵn sàng cao [được thảo luận trong các phần sau], ứng dụng này cung cấp cả tính năng xử lý ngắt kết nối và giúp đảm bảo rằng thư được gửi một cách đáng tin cậy

Lớp

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4, đi kèm với ứng dụng khách AMPS Python, chứa trình xử lý ngắt kết nối và các tính năng khác để xây dựng các ứng dụng có tính sẵn sàng cao.
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4 bao gồm các tính năng để quản lý danh sách máy chủ chuyển đổi dự phòng, tiếp tục đăng ký, xuất bản lại tin nhắn trên chuyến bay và các chức năng khác thường cần thiết để có tính sẵn sàng cao. Phần này đề cập đến việc sử dụng trình xử lý ngắt kết nối tùy chỉnh trong trường hợp hành vi của
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4 không phù hợp với nhu cầu của ứng dụng của bạn

Xử lý ngắt kết nối AMPS mang đến cho bạn khả năng kiểm soát tối ưu và linh hoạt về cách phản hồi khi ngắt kết nối. Ứng dụng của bạn có thể chỉ định chính xác điều gì sẽ xảy ra khi xảy ra ngoại lệ bằng cách cung cấp một hàm cho

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
7, hàm này được gọi bất cứ khi nào xảy ra ngắt kết nối

cho thấy những điều cơ bản

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]

Ví dụ 5. 3. Cung cấp Trình xử lý Ngắt kết nối

Bằng cách tạo trình xử lý ngắt kết nối nâng cao hơn, bạn có thể triển khai logic để làm cho ứng dụng của mình mạnh mẽ hơn nữa. Ví dụ: hãy tưởng tượng bạn có một nhóm máy chủ AMPS được định cấu hình để có tính sẵn sàng cao – bạn có thể triển khai chuyển đổi dự phòng bằng cách thử máy chủ tiếp theo trong danh sách cho đến khi tìm thấy một máy chủ [một phiên bản đơn giản hóa của hành vi được cung cấp bởi

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
8 với
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4]

cho thấy một ví dụ ngắn gọn

class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]

Ví dụ 5. 4. Thực hiện chuyển đổi dự phòng máy khách đơn giản

Sử dụng Heartbeat để phát hiện ngắt kết nối

Ứng dụng khách AMPS bao gồm tính năng nhịp tim để giúp các ứng dụng phát hiện việc ngắt kết nối khỏi máy chủ trong một khoảng thời gian có thể dự đoán được. Không sử dụng nhịp tim, ứng dụng phải dựa vào hệ điều hành để thông báo cho ứng dụng khi xảy ra ngắt kết nối. Đối với các ứng dụng chỉ đơn giản là nhận tin nhắn, không thể biết liệu ổ cắm có bị ngắt kết nối hay đơn giản là không có tin nhắn đến cho máy khách

Khi bạn đặt nhịp tim, ứng dụng khách AMPS sẽ gửi thông báo nhịp tim đến máy chủ AMPS theo định kỳ và đợi một khoảng thời gian xác định để phản hồi. Nếu hệ điều hành báo lỗi khi gửi hoặc nếu máy chủ không phản hồi trong khoảng thời gian đã chỉ định, ứng dụng khách AMPS sẽ coi máy chủ bị ngắt kết nối

Máy khách AMPS xử lý thông báo nhịp tim trên luồng nhận của máy khách, là luồng được sử dụng để xử lý thông báo không đồng bộ. Nếu ứng dụng của bạn sử dụng xử lý thông báo không đồng bộ và chiếm luồng lâu hơn khoảng thời gian nhịp tim, máy khách có thể không phản hồi kịp thời các thông báo nhịp tim và có thể bị ngắt kết nối bởi máy chủ

tin nhắn bất ngờ

Ứng dụng khách AMPS Python xử lý hầu hết các thư đến và thực hiện hành động thích hợp. Một số thông báo không mong muốn hoặc chỉ xảy ra trong những trường hợp rất hiếm. Máy khách AMPS Python cung cấp một cách để máy khách xử lý các thông báo này. Thay vì cung cấp trình xử lý cho tất cả các sự kiện bất thường này, AMPS cung cấp một chức năng xử lý duy nhất cho các thư không thể xử lý trong quá trình xử lý thông thường

Ứng dụng của bạn đăng ký trình xử lý này bằng cách đặt

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
0 cho ứng dụng khách. Trình xử lý này được gọi khi máy khách nhận được thông báo mà bất kỳ trình xử lý nào khác không thể xử lý được. Đây là một sự kiện hiếm gặp và thường biểu thị một tình trạng không mong muốn

Ví dụ: nếu khách hàng xuất bản một thông báo mà AMPS không thể phân tích cú pháp, thì AMPS sẽ trả về xác nhận lỗi. Đây là sự kiện không mong muốn, vì vậy AMPS không bao gồm trình xử lý rõ ràng cho sự kiện này và xác nhận lỗi được nhận trong phương thức đã đăng ký là

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
0

Ứng dụng của bạn chịu trách nhiệm thực hiện mọi hành động khắc phục cần thiết. Ví dụ: nếu xuất bản thông báo không thành công, ứng dụng của bạn có thể quyết định xuất bản lại thông báo, xuất bản thông báo bù, ghi lại lỗi, dừng xuất bản hoàn toàn hoặc bất kỳ hành động nào khác phù hợp

Ngoại lệ chưa được xử lý

Khi sử dụng giao diện không đồng bộ, có thể xảy ra các ngoại lệ không được gửi cho người dùng. Ví dụ: khi một ngoại lệ xảy ra trong quá trình đọc dữ liệu đăng ký từ máy chủ AMPS, ngoại lệ đó sẽ xảy ra trên một luồng bên trong Máy khách Python AMPS. Xem xét ví dụ sau sử dụng giao diện không đồng bộ

class MyApp:
    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self,client]:
        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]

Ví dụ 5. 5. Ngoại lệ đi đâu?

Trong ví dụ này, chúng tôi thiết lập đăng ký để chờ tin nhắn về chủ đề pokes, có thẻ Pokee bắt đầu bằng tên người dùng của chúng tôi. Khi tin nhắn đến, chúng tôi in một tin nhắn ra bàn điều khiển, nhưng nếu không, ứng dụng của chúng tôi sẽ đợi một phím được nhấn

Bên trong ứng dụng khách AMPS, ứng dụng khách tạo một luồng thực thi mới để đọc dữ liệu từ máy chủ và gọi trình xử lý thư và ngắt kết nối trình xử lý khi những sự kiện đó xảy ra. Tuy nhiên, khi các ngoại lệ xảy ra bên trong luồng này, không có trình gọi nào để ném chúng vào và theo mặc định, chúng sẽ bị bỏ qua

Trong các ứng dụng sử dụng giao diện không đồng bộ và trong đó điều quan trọng là phải xử lý mọi sự cố xảy ra khi sử dụng AMPS, bạn có thể đặt

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
2 đến
class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
3 để nhận các ngoại lệ chưa được xử lý này. Thực hiện các sửa đổi được hiển thị trong ví dụ trước của chúng tôi sẽ cho phép các ngoại lệ đó bị bắt và xử lý. Trong trường hợp này, chúng tôi chỉ đơn giản là in những ngoại lệ bị bắt đó ra bàn điều khiển

Trong một số trường hợp, ứng dụng khách AMPS Python có thể gói các ngoại lệ thuộc loại không xác định thành một AMPSException. Trình nghe ngoại lệ của bạn phải luôn bao gồm một khối ngoại trừ cho AMPSException

class MyApp:
    def on_exception[self, e]:
        print "Exception occurred: %s" % str[e]

    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self, client]:
        client.set_exception_listener[self.on_exception]

        # Use the advanced interface to be able to
        # accept input while processing messages.

        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]

Ví dụ 5. 6. Người nghe ngoại lệ

Trong ví dụ này, chúng tôi đã thêm một cuộc gọi tới

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
6, đăng ký một chức năng đơn giản ghi văn bản của ngoại lệ ra bảng điều khiển. Nếu các ngoại lệ được đưa vào trình xử lý thư, các ngoại lệ đó sẽ được ghi vào bảng điều khiển

AMPS ghi lại dấu vết ngăn xếp và cung cấp dấu vết ngăn xếp cho trình xử lý ngoại lệ, nếu phương thức được cung cấp bao gồm tham số cho dấu vết ngăn xếp. Mẫu dưới đây minh họa một cách để làm điều này. [Đối với mục đích mẫu, trình xử lý thông báo luôn đưa ra một ngoại lệ. ]

import AMPS
import time
import traceback

def handler[message]:
    print message
    raise RuntimeError, "in my handler"

def exception_listener[exception, tb]:
    print "EXCEPTION RECEIVED", exception
    if tb is not None:
        traceback.print_tb[tb]

client = AMPS.Client["client"]

client.set_exception_listener[exception_listener]

client.connect["tcp://localhost:9007/amps"]

client.logon[]
client.subscribe[handler,"topic"]
client.publish["topic","data"]
time.sleep[1]
client.close[]

Ví dụ 5. 7. Dấu vết ngăn xếp AMPS

Phát hiện lỗi ghi

Các phương thức

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
7 trong ứng dụng khách Python gửi thông báo sẽ được xuất bản tới AMPS rồi trả về ngay lập tức mà không cần đợi AMPS trả về xác nhận. Tương tự như vậy, các phương thức
class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
8 yêu cầu xóa các thông báo SOW và trả về trước khi AMPS xử lý thông báo và thực hiện việc xóa. Cách tiếp cận này mang lại hiệu suất cao cho các hoạt động không có khả năng thất bại trong sản xuất. Tuy nhiên, điều này có nghĩa là các phương thức trả về trước khi AMPS xử lý lệnh, không có khả năng trả về lỗi trong trường hợp lệnh không thành công

Ứng dụng khách AMPS Python cung cấp một

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
9 được gọi khi ứng dụng khách nhận được xác nhận cho biết không thể duy trì dữ liệu trong AMPS. Như với
class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
0 được mô tả trong , ứng dụng của bạn đăng ký một trình xử lý cho chức năng này. Khi một xác nhận trả về cho biết ghi không thành công, AMPS gọi phương thức xử lý đã đăng ký với thông tin từ thông báo xác nhận, được bổ sung thông tin từ cửa hàng xuất bản ứng dụng khách nếu có sẵn. Khách hàng của bạn có thể ghi lại thông tin này, đưa ra lỗi cho người dùng hoặc thực hiện bất kỳ hành động nào phù hợp với lỗi

Nếu ứng dụng của bạn cần biết liệu xuất bản có thành công hay không và có được duy trì lâu dài hay không, nên sử dụng phương pháp sau

  • Đặt một
    class MyApp:
        def __init__[self, uris]:
            self._currentUri = 0
    
            # Here our application is configured with an array of AMPS server URIs to choose
            # from, instead of a single URI. Our client is constructed and configured with.
            # These will be used in the connect_to_next_uri[] method as explained below.
            self.uris = uris
            self.client = Client[...]
            self.client.set_disconnect_handler[self.connect_to_next_uri]
    
            # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
            # currently disconnected, we manually invoke our disconnect handler to initiate
            # the first connection.
            self.connect_to_next_uri[self.client]
    
        def connect_to_next_uri[self,client]:
    
            # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
            # our array of URIs attempting to connect to each one. In the invoke[] method it
            # attempts to connect to the current URI, and if it is successful, returns
            # immediately. If the connection attempt fails, the exception handler for
            # AMPSException is invoked. In the exception handler, we advance to the next URI,
            # display a warning message, and continue around the loop. This simplistic handler
            # never gives up, but in a typical implementation, you would likely stop
            # attempting to reconnect at some point.
            while true:
                try:
                    client.connect[self.uris[self._currentUri]]
                    client.logon[]
    
                    # At this point the client registers a subscription to the server we have
                    # connected to. It is important to note that, once a new server is connected, it
                    # the responsibility of the application to re-establish any subscriptions placed
                    # previously. This behavior provides an important benefit to your application: one
                    # reason for disconnect is due to a client’s inability to keep up with the rate of
                    # message flow. In a more advanced disconnect handler, you could choose to not re-
                    # establish subscriptions that are the cause of your application's demise.
                    client.subscribe[
                        on_message_handler,
                        "orders",
                        None,
                        timeout=5000
                    ]
                    return
                except AMPSException as e:
                    self._currentUri = [self._currentUri + 1] % len[self.uris]
    
                    print "failed: %s.  Failing over to %s" % [str[e],
                        self.uris[self._currentUri]]
    
    1 trên máy khách. Điều này sẽ đảm bảo rằng các tin nhắn được truyền lại nếu máy khách bị ngắt kết nối trước khi tin nhắn được xác nhận và yêu cầu xác nhận _______12_______2 cho tin nhắn
  • Cài đặt một
    class MyApp:
        def __init__[self, _uri]:
            self.uri = _uri
            self.client = None
            self.client = AMPS.Client[...]
    
            # set_disconnect_handler[] method is called to supply a function for use when AMPS
            # detects a disconnect. At any time, this function may be called by AMPS to
            # indicate that the client has disconnected from the server, and to allow your
            # application to choose what to do about it. The application continues on to
            # connect and subscribe to the orders topic.
            self.client.set_disconnect_handler[self.attempt_reconnection]
            self.client.connect[self.uri]
            self.client.logon[]
    
        # display order data to the user
        def showMessage[self,m]:
    
        # Our disconnect handler’s implementation begins here. In this example, we simply
        # try to reconnect to the original server after a 5 second pause. Errors are
        # likely to occur here, therefore we must have disconnected for a reason, but
        # Client takes care of catching errors from our disconnect handler. If an error
        # occurs in our attempt to reconnect and an exception is thrown by connect[],
        # Client will catch it and absorb it, passing it to the ExceptionListener if
        # registered. If the client is not connected by the time the disconnect handler
        # returns, AMPS throws DisconnectedException.
        def attempt_reconnection[self, client]:
                # simple: just sleep and reconnect
                time.sleep[5]
                self.client.connect[self.uri]
                self.client.logon[]
    
    9. Trong trường hợp AMPS báo cáo lỗi cho một thông báo nhất định, sự kiện đó sẽ được báo cáo cho
    class MyApp:
        def __init__[self, _uri]:
            self.uri = _uri
            self.client = None
            self.client = AMPS.Client[...]
    
            # set_disconnect_handler[] method is called to supply a function for use when AMPS
            # detects a disconnect. At any time, this function may be called by AMPS to
            # indicate that the client has disconnected from the server, and to allow your
            # application to choose what to do about it. The application continues on to
            # connect and subscribe to the orders topic.
            self.client.set_disconnect_handler[self.attempt_reconnection]
            self.client.connect[self.uri]
            self.client.logon[]
    
        # display order data to the user
        def showMessage[self,m]:
    
        # Our disconnect handler’s implementation begins here. In this example, we simply
        # try to reconnect to the original server after a 5 second pause. Errors are
        # likely to occur here, therefore we must have disconnected for a reason, but
        # Client takes care of catching errors from our disconnect handler. If an error
        # occurs in our attempt to reconnect and an exception is thrown by connect[],
        # Client will catch it and absorb it, passing it to the ExceptionListener if
        # registered. If the client is not connected by the time the disconnect handler
        # returns, AMPS throws DisconnectedException.
        def attempt_reconnection[self, client]:
                # simple: just sleep and reconnect
                time.sleep[5]
                self.client.connect[self.uri]
                self.client.logon[]
    
    9
  • Gọi
    class MyApp:
        def __init__[self, uris]:
            self._currentUri = 0
    
            # Here our application is configured with an array of AMPS server URIs to choose
            # from, instead of a single URI. Our client is constructed and configured with.
            # These will be used in the connect_to_next_uri[] method as explained below.
            self.uris = uris
            self.client = Client[...]
            self.client.set_disconnect_handler[self.connect_to_next_uri]
    
            # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
            # currently disconnected, we manually invoke our disconnect handler to initiate
            # the first connection.
            self.connect_to_next_uri[self.client]
    
        def connect_to_next_uri[self,client]:
    
            # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
            # our array of URIs attempting to connect to each one. In the invoke[] method it
            # attempts to connect to the current URI, and if it is successful, returns
            # immediately. If the connection attempt fails, the exception handler for
            # AMPSException is invoked. In the exception handler, we advance to the next URI,
            # display a warning message, and continue around the loop. This simplistic handler
            # never gives up, but in a typical implementation, you would likely stop
            # attempting to reconnect at some point.
            while true:
                try:
                    client.connect[self.uris[self._currentUri]]
                    client.logon[]
    
                    # At this point the client registers a subscription to the server we have
                    # connected to. It is important to note that, once a new server is connected, it
                    # the responsibility of the application to re-establish any subscriptions placed
                    # previously. This behavior provides an important benefit to your application: one
                    # reason for disconnect is due to a client’s inability to keep up with the rate of
                    # message flow. In a more advanced disconnect handler, you could choose to not re-
                    # establish subscriptions that are the cause of your application's demise.
                    client.subscribe[
                        on_message_handler,
                        "orders",
                        None,
                        timeout=5000
                    ]
                    return
                except AMPSException as e:
                    self._currentUri = [self._currentUri + 1] % len[self.uris]
    
                    print "failed: %s.  Failing over to %s" % [str[e],
                        self.uris[self._currentUri]]
    
    5 và xác minh rằng tất cả các tin nhắn vẫn được duy trì trước khi thoát khỏi ứng dụng

Khi không có

class MyApp:
    def __init__[self, _uri]:
        self.uri = _uri
        self.client = None
        self.client = AMPS.Client[...]

        # set_disconnect_handler[] method is called to supply a function for use when AMPS
        # detects a disconnect. At any time, this function may be called by AMPS to
        # indicate that the client has disconnected from the server, and to allow your
        # application to choose what to do about it. The application continues on to
        # connect and subscribe to the orders topic.
        self.client.set_disconnect_handler[self.attempt_reconnection]
        self.client.connect[self.uri]
        self.client.logon[]

    # display order data to the user
    def showMessage[self,m]:

    # Our disconnect handler’s implementation begins here. In this example, we simply
    # try to reconnect to the original server after a 5 second pause. Errors are
    # likely to occur here, therefore we must have disconnected for a reason, but
    # Client takes care of catching errors from our disconnect handler. If an error
    # occurs in our attempt to reconnect and an exception is thrown by connect[],
    # Client will catch it and absorb it, passing it to the ExceptionListener if
    # registered. If the client is not connected by the time the disconnect handler
    # returns, AMPS throws DisconnectedException.
    def attempt_reconnection[self, client]:
            # simple: just sleep and reconnect
            time.sleep[5]
            self.client.connect[self.uri]
            self.client.logon[]
9 nào được đăng ký, các xác nhận cho biết lỗi trong việc duy trì dữ liệu được coi là thông báo không mong muốn và được chuyển đến ____9_______0. Trong trường hợp này, AMPS chỉ cung cấp thông báo xác nhận và không cung cấp thông tin bổ sung từ cửa hàng xuất bản ứng dụng khách

Giám sát trạng thái kết nối

Giao diện máy khách AMPS cung cấp khả năng đặt một hoặc nhiều trình nghe trạng thái kết nối. Trình lắng nghe trạng thái kết nối là lệnh gọi lại được gọi khi ứng dụng khách AMPS phát hiện thay đổi đối với trạng thái kết nối

Máy khách AMPS cung cấp các giá trị trạng thái sau cho trình nghe trạng thái kết nối

Tiểu bangChỉ báoĐã kết nối

Máy khách đã thiết lập kết nối với AMPS. Nếu bạn đang sử dụng một

class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8, điều này sẽ được gửi khi
class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
9 thành công

Nếu bạn đang sử dụng

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4, trạng thái này cho biết rằng phần
class MyApp:
    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self,client]:
        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]
1 của quá trình kết nối và đăng nhập đã hoàn tất. Một
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4 sử dụng trình xử lý ngắt kết nối mặc định sẽ cố gắng đăng nhập ngay sau khi chuyển trạng thái này

Hầu hết các ứng dụng sử dụng

class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8 sẽ cố gắng đăng nhập ngay sau khi lệnh gọi tới ____12_______9 trả về

Ứng dụng không nên gửi lệnh tới AMPS từ trình nghe trạng thái kết nối trong khi ứng dụng khách ở trạng thái này trừ khi ứng dụng biết rằng trạng thái đó đã được gửi từ

class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8 và rằng ____12_______8 không gọi ____15_______7

Đã đăng nhập

Khách hàng đã đăng nhập thành công vào AMPS. Nếu bạn đang sử dụng một

class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8, điều này sẽ được gửi khi
class MyApp:
    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self,client]:
        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]
7 thành công

Nếu bạn đang sử dụng

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4, trạng thái này cho biết rằng phần
class MyApp:
    def on_exception[self, e]:
        print "Exception occurred: %s" % str[e]

    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self, client]:
        client.set_exception_listener[self.on_exception]

        # Use the advanced interface to be able to
        # accept input while processing messages.

        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]
1 của quá trình kết nối và đăng nhập đã hoàn tất

Trạng thái này được phân phối sau khi máy khách đăng nhập, nhưng trước khi quá trình khôi phục trạng thái máy khách hoàn tất. Phục hồi sẽ tiếp tục sau khi cung cấp trạng thái này. ứng dụng không được gửi lệnh tới AMPS từ trình nghe trạng thái kết nối trong khi máy khách ở trạng thái này nếu quá trình khôi phục sẽ diễn ra

Bắt đầu nhịp tim

Khách hàng đã bắt đầu theo dõi nhịp tim thành công với AMPS. Trạng thái này được phân phối nếu ứng dụng đã bật nhịp tim trên máy khách

Trạng thái này được phân phối trước khi quá trình khôi phục trạng thái máy khách hoàn tất. Phục hồi có thể tiếp tục sau khi trạng thái này được chuyển giao. Ứng dụng không được gửi lệnh tới AMPS từ trình nghe trạng thái kết nối cho đến khi máy khách được khôi phục hoàn toàn

Xuất bảnĐã phát lại

Được gửi khi khách hàng đã hoàn thành phát lại cửa hàng xuất bản khi khôi phục sau khi kết nối với AMPS

Trạng thái này được phân phối khi máy khách có cấu hình PublishStore

Nếu khách hàng có bộ quản lý đăng ký, [là mặc định cho

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4], ứng dụng sẽ không gửi lệnh từ trình nghe trạng thái kết nối cho đến khi nhận được trạng thái
class MyApp:
    def on_exception[self, e]:
        print "Exception occurred: %s" % str[e]

    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self, client]:
        client.set_exception_listener[self.on_exception]

        # Use the advanced interface to be able to
        # accept input while processing messages.

        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]
3

đăng ký lại

Được gửi khi khách hàng đã nhập lại đăng ký khi khôi phục sau khi kết nối với AMPS

Trạng thái này được phân phối khi khách hàng đã thiết lập trình quản lý đăng ký [là mặc định cho

def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4]. Đây là bước phục hồi cuối cùng. Một ứng dụng có thể gửi lệnh tới AMPS từ trình nghe trạng thái kết nối sau khi nhận được trạng thái này

DisconnectedMáy khách không được kết nối. Đối với một
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4, điều này có nghĩa là khách hàng sẽ cố gắng kết nối lại với AMPS. Đối với
class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8, điều này có nghĩa là máy khách sẽ gọi trình xử lý ngắt kết nối, nếu một trình xử lý được chỉ định. ShutdownMáy khách đã tắt. Đối với một
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4, điều này có nghĩa là khách hàng sẽ không còn cố gắng kết nối lại với AMPS nữa. Trạng thái này được chuyển giao khi
class MyApp:
    def on_exception[self, e]:
        print "Exception occurred: %s" % str[e]

    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self, client]:
        client.set_exception_listener[self.on_exception]

        # Use the advanced interface to be able to
        # accept input while processing messages.

        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]
8 được gọi trên máy khách hoặc khi người chọn máy chủ yêu cầu
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4 ngừng kết nối lại với AMPS

Bảng 5. 1. Giá trị ConnectionStateListener

Phép liệt kê được cung cấp cho trình lắng nghe trạng thái kết nối cũng bao gồm giá trị

import AMPS
import time
import traceback

def handler[message]:
    print message
    raise RuntimeError, "in my handler"

def exception_listener[exception, tb]:
    print "EXCEPTION RECEIVED", exception
    if tb is not None:
        traceback.print_tb[tb]

client = AMPS.Client["client"]

client.set_exception_listener[exception_listener]

client.connect["tcp://localhost:9007/amps"]

client.logon[]
client.subscribe[handler,"topic"]
client.publish["topic","data"]
time.sleep[1]
client.close[]
0, để sử dụng làm giá trị mặc định hoặc để biểu thị các trạng thái bổ sung trong triển khai
class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8 tùy chỉnh. Việc triển khai 60East của khách hàng không cung cấp trạng thái này

Bảng sau đây hiển thị các ví dụ về tập hợp các trạng thái sẽ được phân phối trong quá trình kết nối, theo thứ tự, tùy thuộc vào tính năng nào của máy khách được đặt. Lưu ý rằng, đối với một thể hiện của lớp

class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
8, bảng này giả định rằng ứng dụng gọi cả
class MyApp:
    def __init__[self, uris]:
        self._currentUri = 0

        # Here our application is configured with an array of AMPS server URIs to choose
        # from, instead of a single URI. Our client is constructed and configured with.
        # These will be used in the connect_to_next_uri[] method as explained below.
        self.uris = uris
        self.client = Client[...]
        self.client.set_disconnect_handler[self.connect_to_next_uri]

        # connect_to_next_uri[] is invoked by our disconnect handler. Since our client is
        # currently disconnected, we manually invoke our disconnect handler to initiate
        # the first connection.
        self.connect_to_next_uri[self.client]

    def connect_to_next_uri[self,client]:

        # In our disconnect handler, we invoke connect_to_next_uri[], which loops around
        # our array of URIs attempting to connect to each one. In the invoke[] method it
        # attempts to connect to the current URI, and if it is successful, returns
        # immediately. If the connection attempt fails, the exception handler for
        # AMPSException is invoked. In the exception handler, we advance to the next URI,
        # display a warning message, and continue around the loop. This simplistic handler
        # never gives up, but in a typical implementation, you would likely stop
        # attempting to reconnect at some point.
        while true:
            try:
                client.connect[self.uris[self._currentUri]]
                client.logon[]

                # At this point the client registers a subscription to the server we have
                # connected to. It is important to note that, once a new server is connected, it
                # the responsibility of the application to re-establish any subscriptions placed
                # previously. This behavior provides an important benefit to your application: one
                # reason for disconnect is due to a client’s inability to keep up with the rate of
                # message flow. In a more advanced disconnect handler, you could choose to not re-
                # establish subscriptions that are the cause of your application's demise.
                client.subscribe[
                    on_message_handler,
                    "orders",
                    None,
                    timeout=5000
                ]
                return
            except AMPSException as e:
                self._currentUri = [self._currentUri + 1] % len[self.uris]

                print "failed: %s.  Failing over to %s" % [str[e],
                    self.uris[self._currentUri]]
9 và
class MyApp:
    def on_message_handler[self,message]:
        print message.get_data[]

    def wait_to_be_poked[self,client]:
        client.subscribe[
            self.on_message_handler,
            "pokes",
            "/Pokee LIKE %s" % getpass.getuser[],
            timeout=5000]
        f = input["Press a key to exit"]
7. Đối với
def create_new_subscription[client]:
    messageStream = None
    topicName = None

    while messageStream is None:

    # attempts to retrieve a topic name [or regular expression] from the user.
    topicName = input["Please enter a topic name"]
    try:

        # If an error occurs when setting up the subscription, the program decides whether
        # or not to try again based on the subclass of AMPSException that is thrown. In
        # this case, if the exception is a BadRegexTopicError, the exception indicates
        # that the user provided a bad regular expression. We would like to give the user
        # a chance to correct, so we ask the user for a new topic name.
        messageStream = client.subscribe[
            topicName,
            None
        ]

    # This line indicates that the program catches the BadRegexTopicError exception
    # and displays a specific error to the user indicating the topic name or
    # expression was invalid. By not returning from the function in this except block,
    # the while loop runs again and the user is asked for another topic name.
    except BadRegexTopicError as e:
        print[
            "Error: bad topic name or regular expression " +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]
        # we'll ask the user for another topic

    # If an AMPS exception of a type other than BadRegexTopicError is thrown by AMPS,
    # it is caught here. In that case, the program emits a different error message to
    # the user.
    except AMPSException as e:
        print [
            "Error: error setting up subscription to topic" +
            topicName +
            ".  The exception was " +
            str[e] +
            "."
        ]

        # At this point the code stops attempting to subscribe to the client by the return
        # None statement.
        return None
   return messageStream
4, bảng này giả định rằng ____1_______4 đang sử dụng _____20_______7 mặc định cho ____1_______4

Lỗi kết nối Python là gì?

Lỗi kết nối − Điều này sẽ được nêu ra nếu có bất kỳ lỗi kết nối nào . Ví dụ mạng bị lỗi, lỗi DNS thì thư viện Request sẽ tăng ngoại lệ ConnectionError. Phản ứng. raise_for_status[] − Dựa trên mã trạng thái i. e. 401, 404, nó sẽ tăng HTTPError cho url được yêu cầu.

Bằng cách nào chúng ta có thể quản lý lỗi trong Python?

Python thử với mệnh đề khác . Đối với những trường hợp này, bạn có thể sử dụng từ khóa khác tùy chọn với câu lệnh thử .

Python xử lý lỗi giá trị như thế nào?

Để giải quyết ValueError trong mã Python, có thể sử dụng khối thử ngoại trừ . Các dòng mã có thể ném ValueError nên được đặt trong khối thử và khối ngoại trừ có thể bắt và xử lý lỗi.

Chủ Đề