package com.wei.jedis;
import com.alibaba.fastjson.JSON;
import jdk.nashorn.internal.parser.JSONParser;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CacheSample {
public CacheSample(){
Jedis jedis = new Jedis("192.168.177.139",6379);
try{
List<Goods> goodsList = new ArrayList<Goods>();
goodsList.add(new Goods(8818, "红富士", "好吃", 23f));
goodsList.add(new Goods(8819, "进口香蕉", "不错", 22f));
goodsList.add(new Goods(8820,"进口苹果", "很脆", 23f));
jedis.auth("123456");
jedis.select(3);
for (Goods goods:goodsList){
String json= JSON.toJSONString(goods);
System.out.println(json);
String key="goods:"+goods.getGoodsId();
jedis.set(key,json);
}
}catch (Exception e){
e.printStackTrace();
}finally {
jedis.close();
}
}
public static void main(String[] args) {
new CacheSample();
System.out.println("请输入要查询的商品编号:");
String goodsId = new Scanner(System.in).next();
Jedis jedis = new Jedis("192.168.177.139", 6379);
try{
jedis.auth("123456");
jedis.select(3);
String key="goods:"+goodsId;
if (jedis.exists(key)) {
String json = jedis.get(key);
System.out.println(json);
Goods goods = JSON.parseObject(json, Goods.class);
System.out.println(goods.getGoodsName());
System.out.println(goods.getPrice());
}else{
System.out.println("您输入的商品编号不存在,请重新输入!");
}
}catch (Exception e){
e.printStackTrace();
}
finally {
jedis.close();
}
}
}
package com.wei.jedis;
public class Goods {
private Integer goodsId;
private String goodsName;
private String description;
private Float price;
public Goods() {
}
public Goods(Integer goodsId, String goodsName, String description, Float price) {
this.goodsId = goodsId;
this.goodsName = goodsName;
this.description = description;
this.price = price;
}
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
}