Then if two processes were to execute this update_safe_ips method at the same time, the “safe_id_temp” list could be [“10.0.0.1”, “10.0.0.2”, “10.0.0.3”,“10.0.0.1”, “10.0.0.2”, “10.0.0.3”]. To protect against this:1.def update_safe_ips
2.safe_ip_ids = SafeIps.select(id).all.map(&:id)
3.temp_list = %Q{ safe_id_temp#{UUID.getUUID} }
4.safe_ip_ids.each { |safe_ip_id| redis.lpush(temp_list, safe_ip_id) }
5.redis.rename temp_list, "safe_ips"
6.end
复制代码This code assumes the existence of a UUID library, which returns a unique ID on every call. Now, if more than one process were to run, they would each create their own temp_list’s. This way, dups will not be created.
Running a piece of code only once
Often times, we would like for a certain piece of code to run successfully exactly once. A classic example of this is something like setting up some auth tokens:1.def setup_auth_tokens
2.username = redis.hget "web_service_creds", "username"
3.pwd= redis.hget "web_service_creds", "pwd"
4.auth_token = get_auth_token username, pwd
5.redis.set "web_service_auth_token", auth_token
6.end
复制代码
|