Ticket #15324: memcached_connection_reuse.patch

File memcached_connection_reuse.patch, 2.2 KB (added by J. David Lowe, 13 years ago)
  • django/core/cache/backends/memcached.py

     
    2828        """
    2929        Implements transparent thread-safe access to a memcached client.
    3030        """
    31         return self._lib.Client(self._servers)
     31        client = getattr(self, 'client', None)
     32        if client:
     33            return client
    3234
     35        client = self._lib.Client(self._servers)
     36
     37        self.client = client
     38
     39        return client
     40
    3341    def _get_memcache_timeout(self, timeout):
    3442        """
    3543        Memcached deals with long (> 30 days) timeouts in a special
  • tests/regressiontests/cache/tests.py

     
    801801        # memcached limits key length to 250
    802802        self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')
    803803
     804    def test_connection_reuse(self):
     805        """
     806        Ensure that we don't create a new memcached connection for every
     807        cache operation.
     808        """
     809
     810        # deliberately bypass the _cache, to ensure that fetching of stats doesn't muddy the results
     811        cache = self.cache._lib.Client(self.cache._servers)
     812        def count_connections():
     813            # get_stats() returns a list of (server, stats_dictionary) tuples
     814            return sum(int(stats[1]['curr_connections']) for stats in cache.get_stats())
     815
     816        # perform a cache operation...
     817        self.cache.set('foo', 'bar')
     818        connections = count_connections()
     819
     820        # ... a second cache operation on the same key should not increase the number of connections!
     821        self.cache.get('foo')
     822        self.assertEqual(connections, count_connections())
     823
    804824MemcachedCacheTests = unittest.skipUnless(settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'), "memcached not available")(MemcachedCacheTests)
    805825
    806826class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
Back to Top