上一篇:Redis从零开始由浅入深(一) 已经介绍了Redis的基本安装以及使用,这篇将讲解Redis在java中的使用
1.创建项目 2.下载jedis.jar驱动包 3.在项目中添加jedis.jar
字符串操作
@Test
public void test ( ) {
Jedis jedis = new Jedis ( "localhost" , 6379 ) ;
System. out. println ( jedis. ping ( ) ) ;
jedis. set ( "name" , "张杰" ) ;
jedis. close ( ) ;
}
@Test
public void test1 ( ) {
Jedis jedis = new Jedis ( "localhost" , 6379 ) ;
System. out. println ( jedis. ping ( ) ) ;
System. out. println ( jedis. get ( "name" ) ) ;
jedis. close ( ) ;
}
列表操作
@Test
public void test2 ( ) {
Jedis jedis = new Jedis ( "localhost" , 6379 ) ;
System. out. println ( jedis. ping ( ) ) ;
jedis. rpush ( "names" , "焊接" ) ;
jedis. rpush ( "names" , "张杰" ) ;
jedis. rpush ( "names" , "焊下澳门" ) ;
jedis. rpush ( "names" , "小狗" ) ;
jedis. rpush ( "names" , "不必" ) ;
jedis. close ( ) ;
}
@Test
public void test3 ( ) {
Jedis jedis = new Jedis ( "localhost" , 6379 ) ;
System. out. println ( jedis. ping ( ) ) ;
List< String> lists = jedis. lrange ( "names" , 0 , - 1 ) ;
for ( String a: lists
) {
System. out. println ( a) ;
}
}
对象类型,可以选择哈希(但是字段较多,强转复杂),但是我这里讲对象序列化
@Test
public void test4 ( ) throws IOException {
Jedis jedis = new Jedis ( "localhost" , 6379 ) ;
User user = new User ( 1 , "张杰" , "8848" ) ;
ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ;
ObjectOutputStream oos = new ObjectOutputStream ( out) ;
oos. writeObject ( user) ;
byte [ ] bytes = out. toByteArray ( ) ;
jedis. set ( "user" . getBytes ( ) , bytes) ;
out. close ( ) ;
oos. close ( ) ;
}
@Test
public void test5 ( ) throws Exception {
Jedis jedis = new Jedis ( "localhost" , 6379 ) ;
byte [ ] bytes = jedis. get ( "user" . getBytes ( ) ) ;
ByteArrayInputStream in = new ByteArrayInputStream ( bytes) ;
ObjectInputStream inputStream = new ObjectInputStream ( in) ;
User user = ( User) inputStream. readObject ( ) ;
System. out. println ( user) ;
}
集合,打开ArrayList的源码,发现ArrayList是可以序列化的,所以可以参照上面的序列化操作,觉得繁琐,是不是可以自己封装成一个Util啊。
public class ArrayList < E> extends AbstractList < E>
implements List < E> , RandomAccess, Cloneable, java. io. Serializable
{
private static final long serialVersionUID = 8683452581122892189 L;
private static final int DEFAULT_CAPACITY = 10 ;
private static final Object[ ] EMPTY_ELEMENTDATA = { } ;