本文为您介绍使用SDK时,可能遇到的问题。
使用SDK时遇到报错ErrCode:SDK.ServerUnreachable怎么办?
问题现象
当您使用SDK时,遇到以下报错信息(请求超时或服务器不可达):
ErrCode:ServerUnreachable
ErrMsg:SocketTimeoutException has occurred on a socket read or accept.
解决方案
在请求中设置ClientToken参数避免多次重试带来重复操作的问题。
说明调用接口前,需配置环境变量,通过环境变量读取访问凭证。更多信息,请参见配置访问凭证。
AccessKey ID和AccessKey Secret的环境变量名:
ALIBABA_CLOUD_ACCESS_KEY_ID、ALIBABA_CLOUD_ACCESS_KEY_SECRET。
Python示例代码如下:
# coding=utf-8 import time import uuid from alibabacloud_ros20190910 import models as ros20190910_models from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_credentials.client import Client as CredClient from alibabacloud_ros20190910.client import Client as ROS20190910Client def generate_client_token(prefix, add_uuid, *suffix_list): if prefix: t = [prefix] else: t = [] if add_uuid: t.append(str(uuid.uuid1())[:-13]) t.extend(suffix_list) r = '_'.join(t) if len(r) > 64: r = r[:64] return r def retry_with_client_token(retry_interval=10, retry_time_out=300): def wrapper(fun): def retry_func(*args, **kwargs): retry_timeout = retry_time_out elapsed_time = 0 # 保证请求的幂等性。该值由客户端生成,并且必须是全局唯一的。 kwargs['client_token'] = generate_client_token(None, True) while True: try: retry_timeout -= elapsed_time return fun(*args, **kwargs) except Exception as e: if isinstance(e, ClientException): if e.error_code != 'SDK.HttpError': raise elif isinstance(e, ServerException): if e.error_code not in ('LastTokenProcessing', 'ServiceUnavailable'): raise else: raise time.sleep(retry_interval) elapsed_time += retry_interval if elapsed_time >= retry_timeout: raise return retry_func return wrapper class RosClient(object): @staticmethod def create_client(): """ 初始化账号Client @return: Client @throws Exception """ cred = CredClient() config = open_api_models.Config( credential=cred ) # 访问的域名 config.endpoint = 'ros.aliyuncs.com' return ROS20190910Client(config) @retry_with_client_token(retry_interval=10, retry_time_out=300) def create_stack(self, region_id, stack_name, template_body, **kwargs): client = self.create_client() create_stack_request = ros20190910_models.CreateStackRequest( region_id=region_id, stack_name=stack_name, # 若模板较大,建议使用TemplateURL参数,避免URL过长,调用失败。 # 您也可以使用Body Param + HTTP POST的方式传递模板内容。 template_body=template_body, disable_rollback=True, **kwargs ) response = client.create_stack(create_stack_request) return response.body if __name__ == '__main__': regin_id = 'cn-beijing' ros_client = RosClient() stack_name = 'test' template_body = "{\"ROSTemplateFormatVersion\": \"2015-09-01\"}" result = ros_client.create_stack(region_id=regin_id, stack_name=stack_name, template_body=template_body) print('stack_id:', result)
如果问题依然存在,请提交工单获取支持。