redis 事务

import redis.clients.jedis.Jedis;

import redis.clients.jedis.Transaction;

public class Simple6 {

public static void main(String[] args) {

isServerRunning();

Jedis client = getConnection();

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");

client.lpush("dat:zhangsan:query".getBytes(), buf);

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));

}

transaction(client);

client.close();

}

//redis事务

private static void transaction(Jedis client){

Transaction tr = client.multi();

tr.hset("user:www", "query", "1");

tr.exec();

}

//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/2395472
今日推荐