首先搭建环境:
junit
junit
4.11
test
redis.clients
jedis
2.1.0
第一步:创建工具类JedisPoolUtil.java用于创建jedis连接池
package ldd.JedisDemo.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisPoolUtil {
// 被volatile修饰的变量不会被本地线程缓存,对该变量的读写都是直接操作共享内存。
private static volatile JedisPool jedisPool = null;
// 私有化静态方法,不能new
private JedisPoolUtil() {};
//对外提供一个get方法
public static JedisPool getJedisPoolInstance() {
if (jedisPool == null) {
synchronized (JedisPoolUtil.class) {
if (jedisPool == null) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxActive(1000);
poolConfig.setMaxIdle(32);
poolConfig.setMaxWait(100 * 1000);
poolConfig.setTestOnBorrow(true);
jedisPool = new JedisPool(poolConfig, "192.168.80.132",6379);
}
}
}
return jedisPool;
}
//释放回池子
public static void release(JedisPool jedisPool,Jedis jedis){
if(jedis != null){
jedisPool.returnResourceObject(jedis);
}
}
}
第二步:创建实体类:User.java
package ldd.JedisDemo.pojo;
public class User{
private int id;
private String userName;
private String sex;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", sex=" + sex + ", age=" + age + "]";
}
}
第三步:jedisTest.java ,测试增删改查
package ldd.JedisDemo;
import java.util.HashMap;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import ldd.JedisDemo.pojo.User;
import ldd.JedisDemo.util.JedisPoolUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class JedisTest {
JedisPool jedisPool = null;
Jedis jedis = null;
@Before
public void before() {
jedisPool = JedisPoolUtil.getJedisPoolInstance();
jedis = jedisPool.getResource();
System.out.println("连通状态:" + jedis.ping());
}
@Test
public void testInsert() {
HashMap map = new HashMap<>();
map.put("id", "1");
map.put("userName", "张三");
map.put("sex", "男");
map.put("age", "33");
jedis.hmset("user1", map);
jedis.hset("user2", "id", "2");
jedis.hset("user2", "userName", "李四");
jedis.hset("user2", "sex", "男");
jedis.hset("user2", "age", "44");
}
@Test
public void testDelete() {
Long del = jedis.del("user1");
System.out.println("删除条数:" + del);
}
@Test
public void testUpdate() {
HashMap map = new HashMap<>();
map.put("id", "1");
map.put("userName", "张三三");
map.put("sex", "男");
map.put("age", "33");
jedis.hmset("user1", map);
}
@Test
public void testSelect() {
List list = jedis.hmget("user1", "id","userName","sex","age");
User user = Trans2User(list);
System.out.println(user);
list = jedis.hmget("user2", "id","userName","sex","age");
user = Trans2User(list);
System.out.println(user);
}
@After
public void after() {
JedisPoolUtil.release(jedisPool, jedis);
}
//Transformation To User
public User Trans2User(List list){
User user = new User();
user.setId(Integer.parseInt(list.get(0)));
user.setUserName(list.get(1));
user.setsex(list.get(2));
user.setAge(Integer.parseInt(list.get(3)));
return user;
}
}
至此jedis的简单使用就结束了,后面附录主从、事务、所有类型数据的操作方法:
1.主从:TestMS.java(Master Slave)
package com.ludada.redis.test;
import redis.clients.jedis.Jedis;
public class TestMS {
public static void main(String[] args) {
//主库Master
Jedis jedis_M = new Jedis("192.168.80.131", 6379);
//从库Slave
Jedis jedis_S = new Jedis("192.168.80.131", 6380);
jedis_S.slaveof("192.168.80.131", 6379);
jedis_M.set("class", "15-Java1");
System.out.println(jedis_S.get("class"));
}
}
2.事务:TestTX.java
package com.ludada.redis.test;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestTX {
public boolean transMethod() throws InterruptedException {
Jedis jedis = new Jedis("192.168.80.131", 6379);
int balance;// 可用余额
int debt;// 欠额
int amtToSubtract = 10;// 实刷额度
jedis.watch("balance");
//jedis.set("balance","200");//模拟其他程序已经修改了该条目
//Thread.sleep(7000);
balance = Integer.parseInt(jedis.get("balance"));
if (balance < amtToSubtract) {
jedis.unwatch();
System.err.println("余额不足!");
return false;
} else {
System.out.println("事务开启");
Transaction transaction = jedis.multi();
transaction.decrBy("balance", amtToSubtract);
transaction.incrBy("debt", amtToSubtract);
List result = transaction.exec();
if(result == null){
//result == null 说明被监控的键在事务执行过程中被修改了
System.err.println("扣款失败,请重试!");
return false;
}
balance = Integer.parseInt(jedis.get("balance"));
debt = Integer.parseInt(jedis.get("debt"));
System.out.println("可用:" + balance);
System.out.println("欠额:" + debt);
return true;
}
}
public static void main(String[] args) throws InterruptedException {
TestTX test = new TestTX();
boolean retValue = test.transMethod();
System.out.println("事务结果:" + retValue);
}
}
3.API:TestAPI.java
package com.ludada.redis.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.Jedis;
public class TestAPI {
public static void main(String[] args) throws InterruptedException {
Jedis jedis = new Jedis("192.168.80.131", 6379);
//key
System.err.println("------------------------------- Key -------------------------------");
Set keys = jedis.keys("*");
for(Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.print(key);
System.out.print(",");
}
System.out.println("");
System.out.println("jedis.exists->"+jedis.exists("K2"));
System.out.println(jedis.ttl("K1"));
System.out.println(jedis.type("K1"));
//String
System.err.println("------------------------------- String -------------------------------");
System.err.println(jedis.getSet("K1", "myRedis"));
System.err.println(jedis.getrange("K1", 0, 4));
jedis.setbit("K1", 2, false);
System.err.println(jedis.getbit("K1", 2));
jedis.setex("K1", 3, "Time To Live");
/*while(jedis.ttl("K1") > 0){
System.err.println(jedis.get("K1")+"->"+jedis.ttl("K1")+"秒");
Thread.sleep(1000);
}*/
jedis.set("K1", "Time To Live");
jedis.append("K1", " End!");
System.err.println(jedis.get("K1"));
//List
System.err.println("------------------------------- List -------------------------------");
jedis.del("mylist");
jedis.lpush("mylist","v1","v2","v3","v4","v5");
List list = jedis.lrange("mylist",0,-1);
for(String element : list){
System.out.println(element);
//Thread.sleep(500);
}
//Set 集合 无序 不可重复
System.err.println("------------------------------- Set -------------------------------");
jedis.sadd("myset1", "1","2","3","4","5");
jedis.sadd("myset2", "2","4","7","6");
System.err.println("myset1 -> "+jedis.smembers("myset1"));
System.err.println("myset2 -> "+jedis.smembers("myset2"));
System.err.println("交集 -> " + jedis.sinter("myset1","myset2"));
System.err.println("并集 -> " + jedis.sunion("myset1","myset2"));
System.err.println("差集 -> " + jedis.sdiff("myset1","myset2"));
//Hash 哈希 KV模式不变,但是value一个键值对
System.err.println("------------------------------- Hash -------------------------------");
jedis.hset("user", "name", "神父");
HashMap map = new HashMap<>();
map.put("sex", "男");
map.put("level", "90");
map.put("address", "Android");
jedis.hmset("user", map);
List userInf= jedis.hmget("user", "name","sex","level","address");
for(String element : userInf){
System.err.println(element);
}
Map map2 = jedis.hgetAll("user");
System.err.println("user:" + map2.toString());
//Zset 有序集合
System.err.println("------------------------------- Zset -------------------------------");
jedis.zadd("myZset", 99.0, "张三");
HashMap zSetMap = new HashMap<>();
zSetMap.put(97.5, "李四");
zSetMap.put(88.0, "王五");
zSetMap.put(63.5, "赵六");
zSetMap.put(100.0, "神父");
jedis.zadd("myZset", zSetMap);
System.err.println("总人数:" + jedis.zcard("myZset"));
System.err.println("大于80分的人数:" + jedis.zcount("myZset", 80.0, 100.0));
System.err.println("按分数从高到低排名:" + jedis.zrevrangeByScore("myZset", 100, 0));
System.err.println("神父的排名是:" + jedis.zrevrank("myZset", "神父")+1);
Set s1 = jedis.zrange("myZset",0,-1);
System.err.println(s1.toString());
for(Iterator iterator1 = s1.iterator();iterator1.hasNext();){
String string = (String) iterator1.next();
System.out.println(string);
}
}
}
Jedis的使用就先写到这里吧