您的位置:首页 > 数据库 > Redis

spring-data-redis RedisTemplate操作

2017-08-23 16:11 706 查看
  使用RedisTemplate来对对象、String等做缓存处理

  首先定义一个对象并重写toString方法

@Test
public void testFastJsonSerializer(){
UserInfo userInfo = new UserInfo();
userInfo.setId(4);
userInfo.setName("1");
userInfo.setSalt("1");
userInfo.setRole("1");
userInfo.setPassword("1");
redisTemplate.opsForValue().set("121", userInfo);
//存储到redis的数据将bean的名字作为一个type存储
/**
* {
"@type": "com.redistest.domain.UserInfo",
"id": 4,
"name": "1",
"password": "1",
"role": "1",
"salt": "1"
}
*/
System.out.println("获取输出");
UserInfo userInfo1  = (UserInfo) redisTemplate.opsForValue().get("121");
System.out.println(userInfo1.toString());

//测试list
/**
* [
{
"@type": "com.redistest.domain.UserInfo",
"id": 4,
"name": "1",
"password": "1",
"role": "1",
"salt": "1"
},
{
"@type": "com.redistest.domain.UserInfo",
"id": 4,
"name": "1",
"password": "1",
"role": "1",
"salt": "1"
}
]
*/
ArrayList<UserInfo> arrayList1 = new ArrayList<>();
arrayList1.add(userInfo);
arrayList1.add(userInfo1);
redisTemplate.opsForValue().set("1212", arrayList1);
System.out.println("获取arrayList输出");
JSONArray jsonArray = (JSONArray) redisTemplate.opsForValue().get("1212");
ArrayList<UserInfo> arrayList11 = jsonArray.toJavaObject(new TypeReference<ArrayList<UserInfo>>(){});
for (UserInfo userInfo2 : arrayList11){
System.out.println(userInfo2);
}

}


View Code

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: