学习redis应用于缓存

学习redis应用于缓存

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.Jedis;

public class Simple3 {

 public static void main(String[] args) {
  
  //连接服务端
  isServerRunning();
  Jedis client = getConnection();
  
  //user表:key-hashmap
  client.hset("user:zhangsan", "query", "1");
  List<String> list = new ArrayList<String>();
  list.add("a");
  list.add("b");
  
  byte[] buf = serilizable(list);
  
  long index = 1;
  //client.lpush("dat:zhangsan:query", "a");
  //dat表:key-list
  client.lpush("dat:zhangsan:query".getBytes(), buf); //写入list
  boolean exists = client.hexists("user:zhangsan", "query");
  if(exists){
   String userVal = client.hget("user:zhangsan", "query");
   System.out.println("userVal = " + userVal);
  }
  
  //client.lpop("dat:zhangsan:query");          //读取
  //client.ltrim("dat:zhangsan:query", -1, 0);  //删除
  
  exists = client.exists("dat:zhangsan:query");
  if(exists){
   //String lVal = client.lindex("dat:zhangsan:query", 1);
   byte[] lVal = client.lpop("dat:zhangsan:query".getBytes());
   Object o = unserilizable(lVal);
   List<String> lo = (List<String>)o;
   System.out.println("lVal = " + lo.get(0));
  }
  client.close();
 }

 //ping
 private static void isServerRunning(){
  String host = "127.0.0.1";
       Jedis jedis = new Jedis(host, 6379);
       System.out.println("Connection to server sucessfully");
       System.out.println("Server is running: "+jedis.ping());
 }
 
 static Jedis getConnection(){
  String host = "127.0.0.1";
       Jedis client = new Jedis(host, 6379);
     return client;
 }
 
 static byte[] serilizable(Object o){
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ObjectOutputStream os = null;
  try {
   os = new ObjectOutputStream(bos);
   os.writeObject(o);
   return bos.toByteArray();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    os.close();
    bos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return null;
 }
 
 static Object unserilizable(byte[] buf){
  ByteArrayInputStream bis = new ByteArrayInputStream(buf);
  ObjectInputStream os = null;
  try {
   os = new ObjectInputStream(bis);
   Object o = os.readObject();
   return o;
  } catch (IOException e) {
   e.printStackTrace();
  } catch(ClassNotFoundException e){
   e.printStackTrace();
  }
  finally{
   try {
    os.close();
    bis.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return null;
 }
 
}

猜你喜欢

转载自zw7534313.iteye.com/blog/2418364