0

我在Elastic Beanstalk上设置了memcached动态添加服务器到memcached

亚马逊的弹性缓存也是一个不错的选择,但由于我的用法很少,因此为我的情况设置一个单独的ec2实例用于全时运行缓存看起来像是矫枉过正,而且它很昂贵。

由于我的应用程序运行在python上,我将使用python客户端与memcached进行通信。

当弹性beanstalk向上/向下缩放时,它会添加/删除一些实例。我想动态地添加/删除memcached服务器以防发生这种情况。缩小时缓存一些缓存似乎完全可以接受。

我该如何做到这一点?

编辑:

我发现了一个类似的问题here

但答案没有提供一个解决这个问题,只是一个解决方法(它建议您使用其他服务,这是免费的,小的使用,网络延迟会减慢速度,所以不是一个好的选择)

回答

0

好吧,这就是我最终做的。

我添加了一个post部署挂钩到我的应用程序。现在,无论何时我部署到Elastic Beanstalk,后置部署钩子中的脚本都会安装memcached,并在本地实例上运行memcached服务器。

之后,脚本连接到RDS实例上的MySQL服务器,并通过输入memcached_servers表来注册它的IP。

现在,在客户端,我们创建一个使用从一小时一次memcached_servers表获取IP和如果服务器已经改变了重新创建一个新的客户一个辅助类使用pylibmc一个memcached客户端。

mc_client.py:

class MCClient(object): 

    _mc_client = None 
    _last_refresh = time.time() 
    _refresh_client_in = 3600 # seconds, 1 hour 
    _servers = [] 

    @staticmethod 
    def client(): 
     if MCClient._mc_client is None or MCClient.client_timeout(): 
      MCClient._mc_client = MCClient.new_memcached_client() 
     return MCClient._mc_client 

    @staticmethod 
    def client_timeout(): 
     return (time.time() - MCClient._last_refresh) > MCClient._refresh_client_in 

    @staticmethod 
    def fetch_memcached_servers(): 
     MCClient._last_refresh = time.time() 
     return list(MemcachedServer.objects.filter(active=True).values_list('ip', flat=True)) 

    @staticmethod 
    def new_memcached_client(): 
     servers = MCClient.fetch_memcached_servers() 
     if MCClient._mc_client is not None and set(MCClient._servers) == set(servers): 
      # do not bother recreating a client, if the servers are still the same 
      return MCClient._mc_client 
     else: 
      MCClient._servers = servers 
      return pylibmc.Client(MCClient._servers, binary=True, behaviors={ 
       'tcp_nodelay': True, 
       'ketama': True, 
       'no_block': True, 
       'num_replicas': min(len(MCClient._servers) - 1, 4), # if a server goes down we don't loose cache 
       'remove_failed': 3, 
       'retry_timeout': 1, 
       'dead_timeout': 60 
      }) 

要获得客户端我做的mc = MCClient.client()。每次Elastic Beanstalk按比例增加/减少memcached服务器都会在一小时内更新。另外,缓存最多可以在4台服务器上进行复制,作为一种安全机制,以便在服务器故障时不会导致缓存丢失。

1

您可以创建一个负载均衡的EB环境,并以您告诉它什么时候放大和缩小的方式进行设置。
在Scaling部分,将“最小实例数”设置为1,将“最大实例数”设置为任何需要的最大缓存主机数。
现在编写一个简短的(python)脚本,用于检查有多少个ec2实例已启动并决定是否仍需要当前memcache框。如果该框需要终止,则使其返回HTTP 500或任何其他错误代码。
现在在“EC2实例运行状况检查”部分中,将“应用程序运行状况检查URL”指向一个短的Python代码,该代码在需要销毁高速缓存服务器时返回错误代码。
这将根据您的指示将应用程序框的数量与缓存服务器的数量绑定。