-
} catch (JedisException e) {
-
log.info("client can't connect server");
-
if(null !=jedis){
-
//redisUtil 对象
-
redisUtil.brokenResource(jedis);
-
}
-
}
-
return v;
-
}
-
@Override
-
public Map<String, V> hget(String cacheKey,Object object) {
-
JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
-
String jCacheKey = json.toString();//将json对象转换为字符串
-
//非空校验
-
if(StringUtils.isEmpty(jCacheKey)){
-
log.info("cacheKey is empty!");
-
return null;
-
}
-
Jedis jedis =null;
-
Map<String,V> result =null;
-
V v=null;
-
try {
-
jedis =redisUtil.getResource();
-
//获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String
-
Map<String,String> map = jedis.hgetAll(jCacheKey);
-
if(null !=map){
-
for(Map.Entry<String, String> entry : map.entrySet()){
-
if(result ==null){
-
result =new HashMap<String,V>();
-
}
-
JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象
-
v = (V)JSONObject.toBean(obj,object.getClass());//将建json对象转换为java对象
-
result.put(entry.getKey(), v);
-
}
-
}
-
} catch (JedisException e) {
-
log.info("client can't connect server");
-
if(null !=jedis){
-
//释放jedis 对象
-
redisUtil.brokenResource(jedis);
-
}
-
}
-
return result;
-
}
5.最后我们来测试一下,注意实际开发中肯定是再service层调用redis的操作接口,我这里写个简单的单元测试
第二种:序列化后存入redis, 我这里用SerializeUtil,不过我推荐使用ProtoBuff更好
-
/**
-
* Created by ${HeJD} on 2018/6/29.
-
*/
-
@RunWith(SpringJUnit4ClassRunner.class)
-
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
-
public class RedisCacheStorageTest {
-
@Autowired
-
private RedisCacheStorage<String,User> redisCacheStorage;
-
@Test
-
public void testSetGet() throws Exception {
-
System.out.print("开始执行测试");
-
User user=new User();
-
user.setUsername("admin7");
-
user.setPassword("admin8");
-
redisCacheStorage.set("Akey7",user);
-
User user2= redisCacheStorage.get("Akey7",new User());
-
System.out.print("======="+user2.getUsername()+"====="+user2.getPassword());
-
}
代码在上一种方式的基础之上,我这里只写一些新的文件和需要修改的地方
1.首先我们需要一个序列化类
public class SerializeUtil {
/*
* 序列化
* */
public static byte[] serizlize(Object object){
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
3.最后测试的代码是一样的
(注意两个地方:1.这里是多实现,要用Qualifier指定注入的bean 2.序列化的方式实体类要实现Serializable接口)
2.我们需要对redis操作接口的实现类修改为另一种方式,我这里新建一个RedisCacheStorageImpl2来做对比
-
@RunWith(S