在 mvnrepository 直接搜索 jedis
,把依赖复制到 pom
就好了。
过程
1 2 3 4 5 6 7 8 9 10 11
| package com.redisc;
import redis.clients.jedis.Jedis;
public class Test { public static void main(String[] args) { Jedis jedis = new Jedis("127.0.0.1", 6379); System.out.println(jedis.ping()); jedis.flushDB(); } }
|
jedis 的操作,几乎和 redis 的命令一摸一样,这里就不说了。
事务
简单例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package com.redisc;
import com.alibaba.fastjson.JSONObject; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction;
public class Test { public static void main(String[] args) { Jedis jedis = new Jedis("127.0.0.1", 6379);
JSONObject jsonObject = new JSONObject(); jsonObject.put("hello", "world"); jsonObject.put("name", "cc"); Transaction multi = jedis.multi(); String result = jsonObject.toJSONString(); try { multi.set("user1", result); multi.set("user2", result);
multi.exec(); } catch (Exception e) { multi.discard(); e.printStackTrace(); } finally { System.out.println(jedis.get("user1")); jedis.close(); } } }
|
加锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| package com.redisc;
import com.alibaba.fastjson.JSONObject; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction;
public class Test { public static void main(String[] args) { Jedis jedis = new Jedis("127.0.0.1", 6379);
jedis.flushDB(); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello", "world"); jsonObject.put("name", "cc"); Transaction multi = jedis.multi(); String result = jsonObject.toJSONString(); jedis.watch(result); try { multi.set("user1", result); multi.set("user2", result);
multi.exec(); } catch (Exception e) { multi.discard(); e.printStackTrace(); } finally { System.out.println(jedis.get("user1")); jedis.close(); } } }
|