java中使用redis(含json類型與java類型裝換) --菜鳥小回

java中使用redis(含json類型與java類型裝換)

  1. 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>

  1. 工具類,用於連接redis
public class JedisConnect {
	public static Jedis Conn(){
		Jedis jedis=new Jedis("120.27.244.176");
		return jedis;
	}
}
  1. 存放一個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);
  1. 獲取redis
//連接
Jedis jedis=JedisConnect.Conn();
//獲取redis中的user(json字符串形式)
String json_user=jedis.get("user");
//json字符串轉對象
User user=JSONObject.parseObject(json_user, User.class);
  1. 模擬數據庫添加靈活使用
//連接
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);

enter description here

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章