问题描述:模仿微博关注-粉丝 redis初步入门
[url]http://blog.nosqlfan.com/html/2938.html?ref=rediszt[/url]
参考那个PHP的例子,我这个是java的,没有达到预期效果。代码如下:
UserService.java接口类
[code="java"]package com.redis.test;
import java.util.Set;
public interface UserService {
// 关注用户
public void follow(String userId);
// 取消关注
public void unfollow(String userId);
// 关注了哪些人
public Set<String> following();
// 被哪些人关注(粉丝)
public Set<String> followedBy();
}[/code]
UserServiceImpl.java接口实现类
[code="java"]package com.redis.test;
import java.util.Set;
import redis.clients.jedis.Jedis;
public class UserServiceImpl implements UserService {
private String userId;
private Jedis redisService;
public UserServiceImpl(String userId) {
this.userId = userId;
this.redisService = new Jedis("localhost");
}
@Override
public void follow(String userId) {
// 添加关注的人
this.redisService.sadd("graph:user:{$this.userId}:following", userId);
// 被关注的人添加
this.redisService.sadd("graph:user:$userId:followed_by", this.userId);
}
@Override
public Set<String> following() {
// 获取所关注的对象集合
return this.redisService
.smembers("graph:user:{$this.userId}:following");
}
@Override
public Set<String> followedBy() {
// 获取被哪些编号进行关注
return this.redisService
.smembers("graph:user:{$this.userId}:followed_by");
}
@Override
public void unfollow(String userId) {
// 移除关注列表
this.redisService.srem("graph:user:{$this.userId}:following", userId);
// 移除被关注列表/粉丝列表
this.redisService.srem("graph:user:$userId:followed_by", this.userId);
}
}[/code]
客户端操作测试类
[code="java"]package com.redis.test;
import java.util.Iterator;
public class UserClient {
/**
*@description
*@param args
*/
public static void main(String[] args) {
UserService user1 = new UserServiceImpl("1");
UserService user2 = new UserServiceImpl("2");
UserService user3 = new UserServiceImpl("3");
//user1关注的人有2 3
user1.follow("2");
user1.follow("3");
Iterator<String> it1 = user1.following().iterator();
System.out.println("user1 following:");
while(it1.hasNext()){
System.out.print(it1.next()+" "); //预计结果为2 3
//实际为1 2 3
}
//user2关注1 3
user2.follow("1");
user2.follow("3");
//user3关注1
user3.follow("1");
Iterator<String> it11 = user1.followedBy().iterator();
System.out.println("\nuser1 followed_by:");
while(it11.hasNext()){
System.out.print(it11.next()+" "); //预计结果为2 3
//实际为 无
}
}
}[/code]
Windows系统、redis2.0.2版本、jedis客户端
这是什么问题呢。