pom.xml:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- redis 客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
测试:
@Test
public void test(){
//创建一个jedis的连接
Jedis jedis=new Jedis("127.0.0.1",6379);
//执行redis命令
jedis.set("mytest","test success");
//从redis中取值
String result=jedis.get("mytest");
//打印结果
System.out.println(result);
//关闭链接
jedis.close();
}
@Test
public void testJedis(){
Jedis jedis=new Jedis("127.0.0.1",6379);
jedis.set("java","100");//设置一个String类型的key
System.out.println(jedis.get("java"));//读取java类型的key
Map<String,String> stuinfo=new HashMap<>();
stuinfo.put("sid","100");
stuinfo.put("sname","老白");
stuinfo.put("class","三班");
jedis.hmset("stuinfo",stuinfo);//
Map<String,String> map=jedis.hgetAll("stuinfo");
System.out.println(map);
System.out.println(stuinfo==map);//内存不相等
Map<String,Double> saleCount=new HashMap<>();
saleCount.put("苹果",34.0);
saleCount.put("香蕉",79.0);
jedis.zadd("salecount",saleCount);
Set<String> resultl=jedis.zrange("salecount",0,-1);
System.out.println(resultl);
jedis.close();
}
jedis操作对象数据
@Test //测试对象的读写
public void testObject(){
//创建一连接池对象
JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
//从连接池中获取一条连接。
Jedis jedis = jedisPool.getResource();
Book b1 = new Book();
b1.setBid(1);
b1.setBname("西游记");
//存储
jedis.hset("b1","bid",b1.getBid()+"");
jedis.hset("b1","bname",b1.getBname()+"");
Book b2 = new Book();
//读取
b2.setBid(Integer.parseInt(jedis.hget("b1","bid")));
b2.setBname(jedis.hget("b1","bname"));
System.out.println(b2);
Student student = new Student();
student.setSid(1);
student.setSname("老白");
student.setAge(18);
student.setBook(b1);//持有关联对象
Gson gson = new Gson();
String json = gson.toJson(student);//转成json字符串
jedis.set("stu",json);//存储json字符串
String json2 = jedis.get("stu");//读取json字符串
//重新构造对象
Student student2 = gson.fromJson(json2,Student.class);
System.out.println(student2);
jedis.close();//归还连接池
jedisPool.close();//关闭连接池
}