java中使用redis(含json類型與java類型裝換)
- pom依賴
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
- 工具類,用於連接redis
public class JedisConnect {
public static Jedis Conn(){
Jedis jedis=new Jedis("120.27.244.176");
return jedis;
}
}
- 存放一個redis,此處模擬session共享
//連接
Jedis jedis=JedisConnect.Conn();
//對象轉json字符串
String json_user=JSONObject.toJSONString(user);
/*
集合轉換成json集合
String JList=JSONArray.toJSONString(list);
*/
//放入redis
jedis.set("user",json_user);
//設置存活時間
jedis.expire("user", 300);
- 獲取redis
//連接
Jedis jedis=JedisConnect.Conn();
//獲取redis中的user(json字符串形式)
String json_user=jedis.get("user");
//json字符串轉對象
User user=JSONObject.parseObject(json_user, User.class);
- 模擬數據庫添加靈活使用
//連接
Jedis jedis=JedisConnect.Conn();
//對象轉json字符串
String reward_json=JSONObject.toJSONString(reward);
/*
字符串轉json對象
JSONObject json_object=JSONObject.parseObject({"Message":"OK"});
json集合轉java集合
List<Goods> list2= JSONArray.parseArray(JList, Goods.class);
*/
//存入的時候使用“表名:主鍵名:主鍵值”形式存儲將自動生成分級目錄
jedis.set("reward:r_id:"+reward.getR_id(), reward_json);