上一节我们学习了redis实现 spring-redis-data的基础知识,这节介绍下存取对象的方法。
一,redis的配置文件如下:
UserInfoDO:
public class UserInfoDO {
private String userId;
private String name;
private String sex;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
二,操作对象存取类
UserRedisClient:
public class UserRedisClient extends RedisBase {
public static String PREFIX_USER = "user:";
public void save(final UserInfoDO user) {
final StringRedisTemplate redisTemplate = getTemplate();
redisTemplate.execute(new RedisCallback<UserInfoDO>() {
public UserInfoDO doInRedis(RedisConnection connection) throws DataAccessException {
String key = PREFIX_USER + user.getUserId();
BoundHashOperations<String, String, String> boundHashOperations = redisTemplate.boundHashOps(key);
Map<String, String> data = new HashMap<String, String>();
data.put("name", user.getName());
data.put("sex", user.getSex());
boundHashOperations.putAll(data);
return null;
}
});
}
public UserInfoDO getUserDoById(final String userId) {
StringRedisTemplate redisTemplate = getTemplate();
return redisTemplate.execute(new RedisCallback<UserInfoDO>() {
public UserInfoDO doInRedis(RedisConnection connection) throws DataAccessException {
String key = PREFIX_USER + userId;
BoundHashOperations<String, String, String> boundHashOperations = getTemplate().boundHashOps(key);
Map<String, String> data = boundHashOperations.entries();
if (data != null) {
UserInfoDO user = new UserInfoDO();
user.setUserId(userId);
user.setName(data.get("name"));
user.setSex(data.get("sex"));
return user;
} else {
return null;
}
}
});
}
}