随业务需求变化而弹性自动扩展

本最佳实践要解决的主要问题是:大多数业务运行都有较为固定的波峰波谷,对云服务器资源的需求也随之变化,如何能动态地增减云服务器资源以满足业务变化的需求。

解决方法是我们可以使用API在业务高峰期自动创建云服务器,高峰期后再自动删除云服务器。从而实现弹性扩展,节省成本。
操作步骤如下:

Step 1:一般情况下,可调用GetMonitorData接口获取云服务器CPU使用率、网络流量等数据。

Step 2:根据自定义的规则(如CPU使用率超过80%或低于30%的阈值)来判断是否需要新增或释放云服务器(如果业务量模式稳定,也可直接生产固定数量的云服务器)。

Step 3:基于自定义镜像加快新服务器的创建与部署(参见本节第1条实践),通过负载均衡来实现游戏服务能力的动态扩展。

部分示意性代码如下:

public class BestPractices {
private static final String ACCESS_KEY_ID = “youraccesskeyid”;
private static final String ACCESS_KEY_SECRET = “youraccesskeysecret”;
private String newInstanceId = “”;
private String slbId = “yourslbid”;
public void scaleUp() throws Exception {
// Could create several instances parallelly too
newInstanceId = createInstance();
startInstance(newInstanceId);
// Add the new created instanceinto the SLB if it is used
addBackendServer(slbId, newInstanceId);
}
public void scaleDown() throws Exception {
removeBackendServer(slbId, newInstanceId);
stopInstance(newInstanceId);
deleteInstance(newInstanceId);
}
private String createInstance() throws Exception {
HashMap ci = newHashMap();
ci.put(“RegionId”, “cn-hangzhou-dg-a01″);
ci.put(“ImageId”, “yourself-image.vhd”);
ci.put(“InstanceType”, “ecs.t1.xsmall”);
ci.put(“SecurityGroupId”, “exsitedsgid-or-newcreatedone”);
//Parse and get the instanceIdfrom the response.
return getInstanceId(newECSRequest().execute(“CreateInstance”, ci));
}

private void deleteInstance(final String instanceId) throws Exception {
newECSRequest().execute(“DeleteInstance”, new HashMap() {
{put(“InstanceId”, instanceId); }
});
}
private void startInstance(final String instanceId) throws Exception {
newECSRequest().execute(“StartInstance”, new HashMap() {
{put(“InstanceId”, instanceId); }
});
}

private void stopInstance(final String instanceId) throws Exception {
newECSRequest().execute(“StopInstance”, new HashMap() {
{put(“InstanceId”, instanceId); }
});
}
private void addBackendServer(final String lbId, StringecsInstanceId) throws Exception {
HashMap ci = newHashMap();
ci.put(“LoadBalancerId”, lbId);
Stringbs = “[{\"ServerId\":\"" ecsInstanceId "\",\"Weight\":\"100\"}]“;
ci.put(“BackendServers”, bs);
newSLBRequest().execute(“AddBackendServers”, ci);
}
private void removeBackendServer(final String lbId, StringecsInstanceId) throws Exception {
HashMap ci = new HashMap();
ci.put(“LoadBalancerId”, lbId);
Stringbs = “[\"ServerId\":\"" ecsInstanceId "\"]“;
ci.put(“BackendServers”, bs);
newSLBRequest().execute(“RemoveBackendServers”, ci);
}
private String getInstanceId(Stringresponse) {
//parse HTTP response and getthe instance id
}
private static ECSAPI newECSRequest() {
return new ECSAPI(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
private static SLBAPI newSLBRequest() {
return new SLBAPI(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}

}

随业务需求变化而弹性自动扩展:等您发表观点呢!

发表评论


快捷键:Ctrl+Enter