-
-
Save yaoyi/6656190 to your computer and use it in GitHub Desktop.
用redis实现了用户之前互相follow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Gemfile | |
gem 'redis', '~> 3.0.1' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/redis.rb | |
$redis = Redis.new(:host => 'localhost', :port => 6379) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/user.rb | |
class User | |
def follow(user) | |
score = Time.now.to_i | |
$redis.multi do | |
$redis.zadd(friendship_redis_key(:following), score, followed.id) | |
$redis.zadd(followed.friendship_redis_key(:followers), score, id) | |
end | |
end | |
def unfollow(user) | |
$redis.multi do | |
$redis.zrem(friendship_redis_key(:following), user.id) | |
$redis.zrem(user.friendship_redis_key(:followers), id) | |
end | |
end | |
def followers | |
User.where(:id => follower_ids) | |
end | |
def following | |
User.where(:id => following_ids) | |
end | |
def follower_ids | |
$redis.zrevrange(friendship_redis_key(:followers), 0, -1) | |
end | |
def following_ids | |
$redis.zrevrange(friendship_redis_key(:following), 0, -1) | |
end | |
def following?(user) | |
!$redis.zscore(friendship_redis_key(:following), user.id).nil? | |
end | |
def followed_by?(user) | |
!$redis.zscore(friendship_redis_key(:followers), user.id).nil? | |
end | |
def followers_count | |
$redis.zcard(friendship_redis_key(:followers)) | |
end | |
def following_count | |
$redis.zcard(friendship_redis_key(:following)) | |
end | |
private | |
# generate redis keys | |
def friendship_redis_key(str) | |
"user:#{id}:#{str}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment