论坛首页 编程语言技术论坛

redis 事务

浏览 2564 次
锁定老帖子 主题:redis 事务
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2017-10-08  

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;

}

 

}

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics