Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。
1、Memcached安装配置
#安装倚赖包 yum install libevent-devel #安装软件 yum -y install memcached #启动服务 /usr/bin/memcached -d -u root -l 192.168.7.102 -m 1024 -p 11211 #命令解释 ''' 启动Memcache 常用参数 -p <num> 设置TCP端口号(默认不设置为: 11211) -U <num> UDP监听端口(默认: 11211, 0 时关闭) -l <ip_addr> 绑定地址(默认:所有都允许,无论内外网或者本机更换IP,有安全隐患,若设置为127.0.0.1就只能本机访问) -d 以daemon方式运行 -u <username> 绑定使用指定用于运行进程<username> -m <num> 允许最大内存用量,单位M (默认: 64 MB) -P <file> 将PID写入文件<file>,这样可以使得后边进行快速进程终止, 需要与-d 一起使用 '''
2、Memcached命令
#测试连接Memcached telnet hostip port telnet 192.168.7.102 11211 #例子 ''' telnet 192.168.7.102 11211 Trying 192.168.7.102... Connected to 192.168.7.102. Escape character is '^]'. #连接成功之后输入命令即可 ''' 存储命令: set/add/replace/append/prepend/cas 获取命令: get/gets 其他命令: delete/stats..
3、python操作Memcached
#linxu下安装pip yum -y install pip #安装python操作Memcached模块 pip install python-memcached
4、Memcached常用操作
import memcache #导入模块 mc = memcache.Client(['10.211.55.4:12000'], debug=True) #连接memcached mc.set("foo", "bar")#插入一条数据 ret = mc.get('foo')#获取一条数据的值 print ret
5、Memcached源码
class Client(threading.local): """Object representing a pool of memcache servers. See L{memcache} for an overview. In all cases where a key is used, the key can be either: 1. A simple hashable type (string, integer, etc.). 2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @group Setup: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog @group Insertion: set, add, replace, set_multi @group Retrieval: get, get_multi @group Integers: incr, decr @group Removal: delete, delete_multi @sort: __init__, set_servers, forget_dead_hosts, disconnect_all, debuglog,\ set, set_multi, add, replace, get, get_multi, incr, decr, delete, delete_multi """ _FLAG_PICKLE = 1 << 0 _FLAG_INTEGER = 1 << 1 _FLAG_LONG = 1 << 2 _FLAG_COMPRESSED = 1 << 3 _SERVER_RETRIES = 10 # how many times to try finding a free server. # exceptions for Client class MemcachedKeyError(Exception): pass class MemcachedKeyLengthError(MemcachedKeyError): pass class MemcachedKeyCharacterError(MemcachedKeyError): pass class MemcachedKeyNoneError(MemcachedKeyError): pass class MemcachedKeyTypeError(MemcachedKeyError): pass class MemcachedStringEncodingError(Exception): pass def __init__(self, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, compressor=zlib.compress, decompressor=zlib.decompress, pload=None, pid=None, server_max_key_length=None, server_max_value_length=None, dead_retry=_DEAD_RETRY, socket_timeout=_SOCKET_TIMEOUT, cache_cas=False, flush_on_reconnect=0, check_keys=True): """Create a new Client object with the given list of servers. @param servers: C{servers} is passed to L{set_servers}. @param debug: whether to display error messages when a server can't be contacted. @param pickleProtocol: number to mandate protocol used by (c)Pickle. @param pickler: optional override of default Pickler to allow subclassing. @param unpickler: optional override of default Unpickler to allow subclassing. @param pload: optional persistent_load function to call on pickle loading. Useful for cPickle since subclassing isn't allowed. @param pid: optional persistent_id function to call on pickle storing. Useful for cPickle since subclassing isn't allowed. @param dead_retry: number of seconds before retrying a blacklisted server. Default to 30 s. @param socket_timeout: timeout in seconds for all calls to a server. Defaults to 3 seconds. @param cache_cas: (default False) If true, cas operations will be cached. WARNING: This cache is not expired internally, if you have a long-running process you will need to expire it manually via client.reset_cas(), or the cache can grow unlimited. @param server_max_key_length: (default SERVER_MAX_KEY_LENGTH) Data that is larger than this will not be sent to the server. @param server_max_value_length: (default SERVER_MAX_VALUE_LENGTH) Data that is larger than this will not be sent to the server. @param flush_on_reconnect: optional flag which prevents a scenario that can cause stale data to be read: If there's more than one memcached server and the connection to one is interrupted, keys that mapped to that server will get reassigned to another. If the first server comes back, those keys will map to it again. If it still has its data, get()s can read stale data that was overwritten on another server. This flag is off by default for backwards compatibility. @param check_keys: (default True) If True, the key is checked to ensure it is the correct length and composed of the right characters. """ super(Client, self).__init__() self.debug = debug self.dead_retry = dead_retry self.socket_timeout = socket_timeout self.flush_on_reconnect = flush_on_reconnect self.set_servers(servers) self.stats = {} self.cache_cas = cache_cas self.reset_cas() self.do_check_key = check_keys # Allow users to modify pickling/unpickling behavior self.pickleProtocol = pickleProtocol self.pickler = pickler self.unpickler = unpickler self.compressor = compressor self.decompressor = decompressor self.persistent_load = pload self.persistent_id = pid self.server_max_key_length = server_max_key_length if self.server_max_key_length is None: self.server_max_key_length = SERVER_MAX_KEY_LENGTH self.server_max_value_length = server_max_value_length if self.server_max_value_length is None: self.server_max_value_length = SERVER_MAX_VALUE_LENGTH # figure out the pickler style file = BytesIO() try: pickler = self.pickler(file, protocol=self.pickleProtocol) self.picklerIsKeyword = True except TypeError: self.picklerIsKeyword = False def _encode_key(self, key): if isinstance(key, tuple): if isinstance(key[1], six.text_type): return (key[0], key[1].encode('utf8')) elif isinstance(key, six.text_type): return key.encode('utf8') return key def _encode_cmd(self, cmd, key, headers, noreply, *args): cmd_bytes = cmd.encode() if six.PY3 else cmd fullcmd = [cmd_bytes, b' ', key] if headers: if six.PY3: headers = headers.encode() fullcmd.append(b' ') fullcmd.append(headers) if noreply: fullcmd.append(b' noreply') if args: fullcmd.append(b' ') fullcmd.extend(args) return b''.join(fullcmd) def reset_cas(self): """Reset the cas cache. This is only used if the Client() object was created with "cache_cas=True". If used, this cache does not expire internally, so it can grow unbounded if you do not clear it yourself. """ self.cas_ids = {} def set_servers(self, servers): """Set the pool of servers used by this client. @param servers: an array of servers. Servers can be passed in two forms: 1. Strings of the form C{"host:port"}, which implies a default weight of 1. 2. Tuples of the form C{("host:port", weight)}, where C{weight} is an integer weight value. """ self.servers = [_Host(s, self.debug, dead_retry=self.dead_retry, socket_timeout=self.socket_timeout, flush_on_reconnect=self.flush_on_reconnect) for s in servers] self._init_buckets() def get_stats(self, stat_args=None): """Get statistics from each of the servers. @param stat_args: Additional arguments to pass to the memcache "stats" command. @return: A list of tuples ( server_identifier, stats_dictionary ). The dictionary contains a number of name/value pairs specifying the name of the status field and the string value associated with it. The values are not converted from strings. """ data = [] for s in self.servers: if not s.connect(): continue if s.family == socket.AF_INET: name = '%s:%s (%s)' % (s.ip, s.port, s.weight) elif s.family == socket.AF_INET6: name = '[%s]:%s (%s)' % (s.ip, s.port, s.weight) else: name = 'unix:%s (%s)' % (s.address, s.weight) if not stat_args: s.send_cmd('stats') else: s.send_cmd('stats ' + stat_args) serverData = {} data.append((name, serverData)) readline = s.readline while 1: line = readline() if not line or line.strip() == 'END': break stats = line.split(' ', 2) serverData[stats[1]] = stats[2] return(data) def get_slabs(self): data = [] for s in self.servers: if not s.connect(): continue if s.family == socket.AF_INET: name = '%s:%s (%s)' % (s.ip, s.port, s.weight) elif s.family == socket.AF_INET6: name = '[%s]:%s (%s)' % (s.ip, s.port, s.weight) else: name = 'unix:%s (%s)' % (s.address, s.weight) serverData = {} data.append((name, serverData)) s.send_cmd('stats items') readline = s.readline while 1: line = readline() if not line or line.strip() == 'END': break item = line.split(' ', 2) # 0 = STAT, 1 = ITEM, 2 = Value slab = item[1].split(':', 2) # 0 = items, 1 = Slab #, 2 = Name if slab[1] not in serverData: serverData[slab[1]] = {} serverData[slab[1]][slab[2]] = item[2] return data def flush_all(self): """Expire all data in memcache servers that are reachable.""" for s in self.servers: if not s.connect(): continue s.flush() def debuglog(self, str): if self.debug: sys.stderr.write("MemCached: %s\n" % str) def _statlog(self, func): if func not in self.stats: self.stats[func] = 1 else: self.stats[func] += 1 def forget_dead_hosts(self): """Reset every host in the pool to an "alive" state.""" for s in self.servers: s.deaduntil = 0 def _init_buckets(self): self.buckets = [] for server in self.servers: for i in range(server.weight): self.buckets.append(server) def _get_server(self, key): if isinstance(key, tuple): serverhash, key = key else: serverhash = serverHashFunction(key) if not self.buckets: return None, None for i in range(Client._SERVER_RETRIES): server = self.buckets[serverhash % len(self.buckets)] if server.connect(): # print("(using server %s)" % server,) return server, key serverhash = serverHashFunction(str(serverhash) + str(i)) return None, None def disconnect_all(self): for s in self.servers: s.close_socket() def delete_multi(self, keys, time=0, key_prefix='', noreply=False): """Delete multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'a1' : 'val1', 'a2' : 'val2'}) >>> mc.get_multi(['a1', 'a2']) == {'a1' : 'val1','a2' : 'val2'} >>> mc.delete_multi(['key1', 'key2']) >>> mc.get_multi(['key1', 'key2']) == {} This method is recommended over iterated regular L{delete}s as it reduces total latency, since your app doesn't have to wait for each round-trip of L{delete} before sending the next one. @param keys: An iterable of keys to clear @param time: number of seconds any subsequent set / update commands should fail. Defaults to 0 for no delay. @param key_prefix: Optional string to prepend to each key when sending to memcache. See docs for L{get_multi} and L{set_multi}. @param noreply: optional parameter instructs the server to not send the reply. @return: 1 if no failure in communication with any memcacheds. @rtype: int """ self._statlog('delete_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys( keys, key_prefix) # send out all requests on each server before reading anything dead_servers = [] rc = 1 for server in six.iterkeys(server_keys): bigcmd = [] write = bigcmd.append extra = ' noreply' if noreply else '' if time is not None: for key in server_keys[server]: # These are mangled keys write("delete %s %d%s\r\n" % (key, time, extra)) else: for key in server_keys[server]: # These are mangled keys write("delete %s%s\r\n" % (key, extra)) try: server.send_cmds(''.join(bigcmd)) except socket.error as msg: rc = 0 if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if noreply, just return if noreply: return rc # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] for server, keys in six.iteritems(server_keys): try: for key in keys: server.expect("DELETED") except socket.error as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) rc = 0 return rc def delete(self, key, time=0, noreply=False): '''Deletes a key from the memcache. @return: Nonzero on success. @param time: number of seconds any subsequent set / update commands should fail. Defaults to None for no delay. @param noreply: optional parameter instructs the server to not send the reply. @rtype: int ''' return self._deletetouch([b'DELETED', b'NOT_FOUND'], "delete", key, time, noreply) def touch(self, key, time=0, noreply=False): '''Updates the expiration time of a key in memcache. @return: Nonzero on success. @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param noreply: optional parameter instructs the server to not send the reply. @rtype: int ''' return self._deletetouch([b'TOUCHED'], "touch", key, time, noreply) def _deletetouch(self, expected, cmd, key, time=0, noreply=False): key = self._encode_key(key) if self.do_check_key: self.check_key(key) server, key = self._get_server(key) if not server: return 0 self._statlog(cmd) if time is not None and time != 0: fullcmd = self._encode_cmd(cmd, key, str(time), noreply) else: fullcmd = self._encode_cmd(cmd, key, None, noreply) try: server.send_cmd(fullcmd) if noreply: return 1 line = server.readline() if line and line.strip() in expected: return 1 self.debuglog('%s expected %s, got: %r' % (cmd, ' or '.join(expected), line)) except socket.error as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return 0 def incr(self, key, delta=1, noreply=False): """Increment value for C{key} by C{delta} Sends a command to the server to atomically increment the value for C{key} by C{delta}, or by 1 if C{delta} is unspecified. Returns None if C{key} doesn't exist on server, otherwise it returns the new value after incrementing. Note that the value for C{key} must already exist in the memcache, and it must be the string representation of an integer. >>> mc.set("counter", "20") # returns 1, indicating success >>> mc.incr("counter") >>> mc.incr("counter") Overflow on server is not checked. Be aware of values approaching 2**32. See L{decr}. @param delta: Integer amount to increment by (should be zero or greater). @param noreply: optional parameter instructs the server to not send the reply. @return: New value after incrementing, no None for noreply or error. @rtype: int """ return self._incrdecr("incr", key, delta, noreply) def decr(self, key, delta=1, noreply=False): """Decrement value for C{key} by C{delta} Like L{incr}, but decrements. Unlike L{incr}, underflow is checked and new values are capped at 0. If server value is 1, a decrement of 2 returns 0, not -1. @param delta: Integer amount to decrement by (should be zero or greater). @param noreply: optional parameter instructs the server to not send the reply. @return: New value after decrementing, or None for noreply or error. @rtype: int """ return self._incrdecr("decr", key, delta, noreply) def _incrdecr(self, cmd, key, delta, noreply=False): key = self._encode_key(key) if self.do_check_key: self.check_key(key) server, key = self._get_server(key) if not server: return None self._statlog(cmd) fullcmd = self._encode_cmd(cmd, key, str(delta), noreply) try: server.send_cmd(fullcmd) if noreply: return line = server.readline() if line is None or line.strip() == b'NOT_FOUND': return None return int(line) except socket.error as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return None def add(self, key, val, time=0, min_compress_len=0, noreply=False): '''Add new key with value. Like L{set}, but only stores in memcache if the key doesn't already exist. @return: Nonzero on success. @rtype: int ''' return self._set("add", key, val, time, min_compress_len, noreply) def append(self, key, val, time=0, min_compress_len=0, noreply=False): '''Append the value to the end of the existing key's value. Only stores in memcache if key already exists. Also see L{prepend}. @return: Nonzero on success. @rtype: int ''' return self._set("append", key, val, time, min_compress_len, noreply) def prepend(self, key, val, time=0, min_compress_len=0, noreply=False): '''Prepend the value to the beginning of the existing key's value. Only stores in memcache if key already exists. Also see L{append}. @return: Nonzero on success. @rtype: int ''' return self._set("prepend", key, val, time, min_compress_len, noreply) def replace(self, key, val, time=0, min_compress_len=0, noreply=False): '''Replace existing key with value. Like L{set}, but only stores in memcache if the key already exists. The opposite of L{add}. @return: Nonzero on success. @rtype: int ''' return self._set("replace", key, val, time, min_compress_len, noreply) def set(self, key, val, time=0, min_compress_len=0, noreply=False): '''Unconditionally sets a key to a given value in the memcache. The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the compressor routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. @param noreply: optional parameter instructs the server to not send the reply. ''' return self._set("set", key, val, time, min_compress_len, noreply) def cas(self, key, val, time=0, min_compress_len=0, noreply=False): '''Check and set (CAS) Sets a key to a given value in the memcache if it hasn't been altered since last fetched. (See L{gets}). The C{key} can optionally be an tuple, with the first element being the server hash value and the second being the key. If you want to avoid making this module calculate a hash value. You may prefer, for example, to keep all of a given user's objects on the same memcache server, so you could use the user's unique id as the hash value. @return: Nonzero on success. @rtype: int @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param min_compress_len: The threshold length to kick in auto-compression of the value using the compressor routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. @param noreply: optional parameter instructs the server to not send the reply. ''' return self._set("cas", key, val, time, min_compress_len, noreply) def _map_and_prefix_keys(self, key_iterable, key_prefix): """Compute the mapping of server (_Host instance) -> list of keys to stuff onto that server, as well as the mapping of prefixed key -> original key. """ key_prefix = self._encode_key(key_prefix) # Check it just once ... key_extra_len = len(key_prefix) if key_prefix and self.do_check_key: self.check_key(key_prefix) # server (_Host) -> list of unprefixed server keys in mapping server_keys = {} prefixed_to_orig_key = {} # build up a list for each server of all the keys we want. for orig_key in key_iterable: if isinstance(orig_key, tuple): # Tuple of hashvalue, key ala _get_server(). Caller is # essentially telling us what server to stuff this on. # Ensure call to _get_server gets a Tuple as well. serverhash, key = orig_key key = self._encode_key(key) if not isinstance(key, six.binary_type): # set_multi supports int / long keys. key = str(key) if six.PY3: key = key.encode('utf8') bytes_orig_key = key # Gotta pre-mangle key before hashing to a # server. Returns the mangled key. server, key = self._get_server( (serverhash, key_prefix + key)) orig_key = orig_key[1] else: key = self._encode_key(orig_key) if not isinstance(key, six.binary_type): # set_multi supports int / long keys. key = str(key) if six.PY3: key = key.encode('utf8') bytes_orig_key = key server, key = self._get_server(key_prefix + key) # alert when passed in key is None if orig_key is None: self.check_key(orig_key, key_extra_len=key_extra_len) # Now check to make sure key length is proper ... if self.do_check_key: self.check_key(bytes_orig_key, key_extra_len=key_extra_len) if not server: continue if server not in server_keys: server_keys[server] = [] server_keys[server].append(key) prefixed_to_orig_key[key] = orig_key return (server_keys, prefixed_to_orig_key) def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0, noreply=False): '''Sets multiple keys in the memcache doing just one query. >>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'}) >>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', ... 'key2' : 'val2'} This method is recommended over regular L{set} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn't have to wait for each round-trip of L{set} before sending the next one. @param mapping: A dict of key/value pairs to set. @param time: Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. @param key_prefix: Optional string to prepend to each key when sending to memcache. Allows you to efficiently stuff these keys into a pseudo-namespace in memcache: >>> notset_keys = mc.set_multi( ... {'key1' : 'val1', 'key2' : 'val2'}, ... key_prefix='subspace_') >>> len(notset_keys) == 0 True >>> mc.get_multi(['subspace_key1', ... 'subspace_key2']) == {'subspace_key1': 'val1', ... 'subspace_key2' : 'val2'} True Causes key 'subspace_key1' and 'subspace_key2' to be set. Useful in conjunction with a higher-level layer which applies namespaces to data in memcache. In this case, the return result would be the list of notset original keys, prefix not applied. @param min_compress_len: The threshold length to kick in auto-compression of the value using the compressor routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. @param noreply: optional parameter instructs the server to not send the reply. @return: List of keys which failed to be stored [ memcache out of memory, etc. ]. @rtype: list ''' self._statlog('set_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys( six.iterkeys(mapping), key_prefix) # send out all requests on each server before reading anything dead_servers = [] notstored = [] # original keys. for server in six.iterkeys(server_keys): bigcmd = [] write = bigcmd.append try: for key in server_keys[server]: # These are mangled keys store_info = self._val_to_store_info( mapping[prefixed_to_orig_key[key]], min_compress_len) if store_info: flags, len_val, val = store_info headers = "%d %d %d" % (flags, time, len_val) fullcmd = self._encode_cmd('set', key, headers, noreply, b'\r\n', val, b'\r\n') write(fullcmd) else: notstored.append(prefixed_to_orig_key[key]) server.send_cmds(b''.join(bigcmd)) except socket.error as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if noreply, just return early if noreply: return notstored # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] # short-circuit if there are no servers, just return all keys if not server_keys: return(mapping.keys()) for server, keys in six.iteritems(server_keys): try: for key in keys: if server.readline() == 'STORED': continue else: # un-mangle. notstored.append(prefixed_to_orig_key[key]) except (_Error, socket.error) as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return notstored def _val_to_store_info(self, val, min_compress_len): """Transform val to a storable representation. Returns a tuple of the flags, the length of the new value, and the new value itself. """ flags = 0 if isinstance(val, six.binary_type): pass elif isinstance(val, six.text_type): val = val.encode('utf-8') elif isinstance(val, int): flags |= Client._FLAG_INTEGER val = '%d' % val if six.PY3: val = val.encode('ascii') # force no attempt to compress this silly string. min_compress_len = 0 elif six.PY2 and isinstance(val, long): flags |= Client._FLAG_LONG val = str(val) if six.PY3: val = val.encode('ascii') # force no attempt to compress this silly string. min_compress_len = 0 else: flags |= Client._FLAG_PICKLE file = BytesIO() if self.picklerIsKeyword: pickler = self.pickler(file, protocol=self.pickleProtocol) else: pickler = self.pickler(file, self.pickleProtocol) if self.persistent_id: pickler.persistent_id = self.persistent_id pickler.dump(val) val = file.getvalue() lv = len(val) # We should try to compress if min_compress_len > 0 # and this string is longer than our min threshold. if min_compress_len and lv > min_compress_len: comp_val = self.compressor(val) # Only retain the result if the compression result is smaller # than the original. if len(comp_val) < lv: flags |= Client._FLAG_COMPRESSED val = comp_val # silently do not store if value length exceeds maximum if (self.server_max_value_length != 0 and len(val) > self.server_max_value_length): return(0) return (flags, len(val), val) def _set(self, cmd, key, val, time, min_compress_len=0, noreply=False): key = self._encode_key(key) if self.do_check_key: self.check_key(key) server, key = self._get_server(key) if not server: return 0 def _unsafe_set(): self._statlog(cmd) if cmd == 'cas' and key not in self.cas_ids: return self._set('set', key, val, time, min_compress_len, noreply) store_info = self._val_to_store_info(val, min_compress_len) if not store_info: return(0) flags, len_val, encoded_val = store_info if cmd == 'cas': headers = ("%d %d %d %d" % (flags, time, len_val, self.cas_ids[key])) else: headers = "%d %d %d" % (flags, time, len_val) fullcmd = self._encode_cmd(cmd, key, headers, noreply, b'\r\n', encoded_val) try: server.send_cmd(fullcmd) if noreply: return True return(server.expect(b"STORED", raise_exception=True) == b"STORED") except socket.error as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return 0 try: return _unsafe_set() except _ConnectionDeadError: # retry once try: if server._get_socket(): return _unsafe_set() except (_ConnectionDeadError, socket.error) as msg: server.mark_dead(msg) return 0 def _get(self, cmd, key): key = self._encode_key(key) if self.do_check_key: self.check_key(key) server, key = self._get_server(key) if not server: return None def _unsafe_get(): self._statlog(cmd) try: cmd_bytes = cmd.encode() if six.PY3 else cmd fullcmd = b''.join((cmd_bytes, b' ', key)) server.send_cmd(fullcmd) rkey = flags = rlen = cas_id = None if cmd == 'gets': rkey, flags, rlen, cas_id, = self._expect_cas_value( server, raise_exception=True ) if rkey and self.cache_cas: self.cas_ids[rkey] = cas_id else: rkey, flags, rlen, = self._expectvalue( server, raise_exception=True ) if not rkey: return None try: value = self._recv_value(server, flags, rlen) finally: server.expect(b"END", raise_exception=True) except (_Error, socket.error) as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return None return value try: return _unsafe_get() except _ConnectionDeadError: # retry once try: if server.connect(): return _unsafe_get() return None except (_ConnectionDeadError, socket.error) as msg: server.mark_dead(msg) return None def get(self, key): '''Retrieves a key from the memcache. @return: The value or None. ''' return self._get('get', key) def gets(self, key): '''Retrieves a key from the memcache. Used in conjunction with 'cas'. @return: The value or None. ''' return self._get('gets', key) def get_multi(self, keys, key_prefix=''): '''Retrieves multiple keys from the memcache doing just one query. >>> success = mc.set("foo", "bar") >>> success = mc.set("baz", 42) >>> mc.get_multi(["foo", "baz", "foobar"]) == { ... "foo": "bar", "baz": 42 ... } >>> mc.set_multi({'k1' : 1, 'k2' : 2}, key_prefix='pfx_') == [] This looks up keys 'pfx_k1', 'pfx_k2', ... . Returned dict will just have unprefixed keys 'k1', 'k2'. >>> mc.get_multi(['k1', 'k2', 'nonexist'], ... key_prefix='pfx_') == {'k1' : 1, 'k2' : 2} get_mult [ and L{set_multi} ] can take str()-ables like ints / longs as keys too. Such as your db pri key fields. They're rotored through str() before being passed off to memcache, with or without the use of a key_prefix. In this mode, the key_prefix could be a table name, and the key itself a db primary key number. >>> mc.set_multi({42: 'douglass adams', ... 46: 'and 2 just ahead of me'}, ... key_prefix='numkeys_') == [] >>> mc.get_multi([46, 42], key_prefix='numkeys_') == { ... 42: 'douglass adams', ... 46: 'and 2 just ahead of me' ... } This method is recommended over regular L{get} as it lowers the number of total packets flying around your network, reducing total latency, since your app doesn't have to wait for each round-trip of L{get} before sending the next one. See also L{set_multi}. @param keys: An array of keys. @param key_prefix: A string to prefix each key when we communicate with memcache. Facilitates pseudo-namespaces within memcache. Returned dictionary keys will not have this prefix. @return: A dictionary of key/value pairs that were available. If key_prefix was provided, the keys in the retured dictionary will not have it present. ''' self._statlog('get_multi') server_keys, prefixed_to_orig_key = self._map_and_prefix_keys( keys, key_prefix) # send out all requests on each server before reading anything dead_servers = [] for server in six.iterkeys(server_keys): try: fullcmd = b"get " + b" ".join(server_keys[server]) server.send_cmd(fullcmd) except socket.error as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) dead_servers.append(server) # if any servers died on the way, don't expect them to respond. for server in dead_servers: del server_keys[server] retvals = {} for server in six.iterkeys(server_keys): try: line = server.readline() while line and line != b'END': rkey, flags, rlen = self._expectvalue(server, line) # Bo Yang reports that this can sometimes be None if rkey is not None: val = self._recv_value(server, flags, rlen) # un-prefix returned key. retvals[prefixed_to_orig_key[rkey]] = val line = server.readline() except (_Error, socket.error) as msg: if isinstance(msg, tuple): msg = msg[1] server.mark_dead(msg) return retvals def _expect_cas_value(self, server, line=None, raise_exception=False): if not line: line = server.readline(raise_exception) if line and line[:5] == b'VALUE': resp, rkey, flags, len, cas_id = line.split() return (rkey, int(flags), int(len), int(cas_id)) else: return (None, None, None, None) def _expectvalue(self, server, line=None, raise_exception=False): if not line: line = server.readline(raise_exception) if line and line[:5] == b'VALUE': resp, rkey, flags, len = line.split() flags = int(flags) rlen = int(len) return (rkey, flags, rlen) else: return (None, None, None) def _recv_value(self, server, flags, rlen): rlen += 2 # include \r\n buf = server.recv(rlen) if len(buf) != rlen: raise _Error("received %d bytes when expecting %d" % (len(buf), rlen)) if len(buf) == rlen: buf = buf[:-2] # strip \r\n if flags & Client._FLAG_COMPRESSED: buf = self.decompressor(buf) flags &= ~Client._FLAG_COMPRESSED if flags == 0: # Bare string if six.PY3: val = buf.decode('utf8') else: val = buf elif flags & Client._FLAG_INTEGER: val = int(buf) elif flags & Client._FLAG_LONG: if six.PY3: val = int(buf) else: val = long(buf) elif flags & Client._FLAG_PICKLE: try: file = BytesIO(buf) unpickler = self.unpickler(file) if self.persistent_load: unpickler.persistent_load = self.persistent_load val = unpickler.load() except Exception as e: self.debuglog('Pickle error: %s\n' % e) return None else: self.debuglog("unknown flags on get: %x\n" % flags) raise ValueError('Unknown flags on get: %x' % flags) return val def check_key(self, key, key_extra_len=0): """Checks sanity of key. Fails if: Key length is > SERVER_MAX_KEY_LENGTH (Raises MemcachedKeyLength). Contains control characters (Raises MemcachedKeyCharacterError). Is not a string (Raises MemcachedStringEncodingError) Is an unicode string (Raises MemcachedStringEncodingError) Is not a string (Raises MemcachedKeyError) Is None (Raises MemcachedKeyError) """ if isinstance(key, tuple): key = key[1] if key is None: raise Client.MemcachedKeyNoneError("Key is None") if key is '': if key_extra_len is 0: raise Client.MemcachedKeyNoneError("Key is empty") # key is empty but there is some other component to key return if not isinstance(key, six.binary_type): raise Client.MemcachedKeyTypeError("Key must be a binary string") if (self.server_max_key_length != 0 and len(key) + key_extra_len > self.server_max_key_length): raise Client.MemcachedKeyLengthError( "Key length is > %s" % self.server_max_key_length ) if not valid_key_chars_re.match(key): raise Client.MemcachedKeyCharacterError( "Control/space characters not allowed (key=%r)" % key)
6、Memcached与Redis的不同
Redis和Memcached区别
Memcached真的过时了吗?
总结:
根据不同的场景来合理的使用不同的程序!各有优点。
Memcached集群配置(有兴趣的可以看下)
非常详细的Redis数据类型介绍和安装操作
Redis命令参考中文网站
Redis源站官网
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都 支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排 序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文 件,并且在此基础上实现了master-slave(主从)同步。
1、Redis安装&操作
1、检查配置环境 检查gcc是否安装,如果没有安装:yum -y install gcc 2、下载安装Redis cd /opt/ wget http://download.redis.io/releases/redis-3.0.4.tar.gz #这里下载可以登录官网查看最新的Redis tar -xvf redis-3.0.4.tar.gz make make install cd /opt/redis-3.0.4/src/ make test 安装中可能遇到的问题: zmalloc.h:50:31: error: jemalloc/jemalloc.h: No such file or directory zmalloc.h:55:2: error: #error "Newer version of jemalloc required" Allocator --------------------------------------------------------------------------------------------------------- Selecting a non-default memory allocator when building Redis is done by setting the `MALLOC` environment variable. Redis is compiled and linked against libc malloc by default, with the exception of jemalloc being the default on Linux systems. This default was picked because jemalloc has proven to have fewer fragmentation problems than libc malloc. To force compiling against libc malloc, use: % make MALLOC=libc To compile against jemalloc on Mac OS X systems, use: % make MALLOC=jemalloc allocator(分配算符),如果有MALLOC这个环境变量,会有用这个环境变量的 去建立Redis。 而且libc 并不是默认的分配器,默认的是jemalloc! 因为jemalloc被证明有更少的fragmentation problems比libc。 但是如果你又没有jemalloc 而只有 libc 当然 make 出错。 所以加这么一个参数。 make MALLOC=libc --------------------------------------------------------------------------------------------------------- 3、配置redis cp /opt/redis-3.0.4/utils/redis_init_script /etc/init.d/redis #复制管理脚本 chmod +x /etc/init.d/redis mkdir /etc/redis cp /opt/redis-3.0.4/redis.conf /etc/redis/6379.conf 4、修改redis启动模式 默认Redis启动的时候是启动在前台的,把他改为启动在后台 vim /etc/redis/6379.conf daemonize no 改为 daemonize yes 5、Redis加入到系统服务并设置为开机启动 首先修改Redis启动脚本: vim /etc/init.d/redis #chkconfig: 35 95 95 在第三行加上即可 添加系统服务:chkconfig --add redis 设置开机启动:chkconfig redis on 检查服务状态:chkconfig --list redis 6、指定日志存放位置&PID文件&数据库文件存放位置(下一边写持久化) vim /etc/redis/6379.conf logfile "/var/log/redis.log" 指定日志文件如果不指定就会在控制台输出 pidfile /var/run/redis_6379.pid dir ./ 这个是指默认的持久化配置文件放在那里!建议修改下! pidfile如果不修改使用默认的话就会报错: 原因是在/etc/init.d/redis里指定的默认PID是:PIDFILE=/var/run/redis_${REDISPORT}.pid 但是默认配置文件:/etc/redis/6379.conf(咱们自己从解压包里复制的里的默认是:pidfile /var/run/redis.pid)
SET 设置Key GET 判断Key的值 EXISTS 判断Key是否存在 KEYS * 显示所有的Key DEL 删除指定Key TYPE 获取Key类型 注:Redis是不区分大小写的,命令最好使用大写这样能区分是命令还是参数! 1、set的例子: 192.168.0.201:6379> SET hello hehe OK 192.168.0.201:6379> GET hello "hehe" 2、设置多个key value 然后使用使用keys * 去查看所有 192.168.0.201:6379> SET hello1 hehe1 OK 192.168.0.201:6379> SET hello2 hehe2 OK 192.168.0.201:6379> KEYS * 1) "hello1" 2) "hello" 3) "hello2" KEY匹配方式: ?匹配单个 *匹配所有 3、判断key是否存在 判断Key是否存在使用:EXISTS 他返回的是整形:0不存在,1存在 192.168.0.201:6379> EXISTS hello (integer) 1 192.168.0.201:6379> EXISTS hehe (integer) 0 4、删除KEY 192.168.0.201:6379> DEL hello (integer) 1 #这里的1是数量 删除多个测试下: 192.168.0.201:6379> DEL hello1 hello2 (integer) 2 5、查看类型TYPE 只要用set类型就是字符串。查看类型命令用TYPE 192.168.0.201:6379> TYPE hello string 6、Keyspace redis是支持多个实例的默认最多16个,可以修改配置文件来支持更多! 使用INFO命令查看! # Keyspace db0:keys=1,expires=0,avg_ttl=0 db0 :这个可以理解为命名空间。最多支持16个,使用SELECT 去切换 192.168.0.201:6379> SELECT 1 OK 尝试添加一个key-value SET db1 hehe 然后在使用INFO看下 # Keyspace db0:keys=1,expires=0,avg_ttl=0 db1:keys=1,expires=0,avg_ttl=0
2、python操作Redis
#安装模块 pip install redis #详见GitHub https://github.com/WoLpH/redis-py
3、常用操作
基本命令:
redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令,Redis是StrictRedis的子类,用于向后兼容旧版本的redis-py
#r = redis.Redis 他是StrictRedis的子类,Redis继承了StrictRedis,所以一般我们都用Redis = Redis(StrictRedis):
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' import redis r = redis.Redis(host='192.168.17.15',port=6379) #设置连接的主机和端口 r.set('name','luotianshuai')#添加一条记录 print r.get('name')#获取一条记录
连接池:
redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数 Redis,这样就可以实现多个Redis实例共享一个连接池。
rpool = redis.ConnectionPool(host='192.168.17.15',port=6379) #创建连接池连接对象 r = redis.Redis(connection_pool=rpool)#把创建的对象赋值给connection_pool r.set('username','luotianshuai') #添加一条记录 print r.get('username')#获取一条记录
管道:
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。
原子操作(atomic operation)是不需要synchronized",这是Java多线程编程的老生常谈了。所谓原子操作是指不会被线程调度机制打断的操作;这种操作一旦开始,就一直运行到结束,中间不会有任何 context switch (切换到另一个线程)
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' import redis pool = redis.ConnectionPool(host='192.168.17.15',port='6379') r = redis.Redis(connection_pool=pool) pipe = r.pipeline(transaction=True) r.set('name','luotianshuai') r.set('age',18) pipe.execute()
订阅与发布
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' import redis class RedisHelper(object): def __init__(self):#构造方法 self.__conn = redis.Redis(host='192.168.17.15',port=6379)#连接Redis self.channel = 'monitoring' #定义channel名称 def publish(self,msg):#定义发布方法 self.__conn.publish(self.channel,msg) return True def subscribe(self):#定义订阅方法 pub = self.__conn.pubsub()#连接channel pub.subscribe(self.channel)#订阅channel pub.parse_response() return pub
发布者
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' from redis_helper import RedisHelper obj = RedisHelper() #实例化方法 obj.publish('hello') #执行发布
订阅者
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' from redis_helper import RedisHelper obj = RedisHelper() #实例化对象 redis_sub = obj.subscribe()#调用订阅方法 while True: msg = redis_sub.parse_response()#接收发布消息 print msg
注:订阅和发布就类似收音机,发布者和订阅者都在一个相同的频道里,当发布者发布了一条消息的时候,所有的订阅者将会收到发布者发布的信息
1、解释
RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。他遵循Mozilla Public License开源协议。
MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法。应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们。消 息传递指的是程序之间通过在消息中发送数据进行通信,而不是通过直接调用彼此来通信,直接调用通常是用于诸如远程过程调用的技术。排队指的是应用程序通过 队列来通信。队列的使用除去了接收和发送应用程序同时执行的要求。
2、安装
RabbitMQ
#安装配置epel源 $ rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm #安装erlang $ yum -y install erlang #安装RabbitMQ $ yum -y install rabbitmq-server #启动、关闭服务 service rabbitmq-server start/stop
API
pip install pika or easy_install pika or 源码 https://pypi.python.org/pypi/pika
3、基于Queue实现,生产者消费者模型
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'luotianshuai' import Queue import threading messagequeue = Queue.Queue(10) #创建最多有10个元素的队列 def producer(i):#创建生产者 while True: messagequeue.put(i) def consumer(i):#创建消费者 while True: messagequeue.get(i) for i in range(5): #创建5个线程不断的生产 t = threading.Thread(target=producer,args=(i,)) t.start() for i in range(2): #创建5个线程不断的消费 t = threading.Thread(target=consumer,args=(i,)) t.start()
4、RabbitMQ生产者消费者模型
对于RabbitMQ来说,生产和消费不再针对内存里的一个Queue对象,而是某台服务器上的RabbitMQ Server实现的消息队列。
未完待续。。。。
更多请看:http://www.cnblogs.com/wupeiqi/articles/5132791.html