Jedis 是 Redis 官方首选的 Java 客户端开发包
官网地址:https://github.com/xetorthio/jedis
在正式使用jedis之前,需要修改redis.conf文件中的两个参数,开启redis的远程访问,否则无法连接redis
(1).注释掉bing 127.0.0.1,否则只能本机访问
(2).关闭redis的保护模式
官网下载jedis的jar,笔者安装的redis版本为4.0.1,jedis操作redis需要引入jedis-2.9.0.jar,如果想要使用redis的连接池的话,还需要commons-pool2-2.4.1.jar
通过jedis完成对redis存取值的操作,代码如下
package jedistest;
import redis.clients.jedis.Jedis;
/**
* Jedis 操作 Redis
*/
public class JedisTest {
private static Jedis jedis;
public static void main(String[] args) {
jedis = new Jedis("192.168.242.161", 6379);
jedis.set("name", "zhangsan");
String value = jedis.get("name");
System.out.println("name = " + value);
}
}
输出结果:
name = zhangsan
一般我们不建议通过上面的方式来操作redis,因为每一次jedis操作都要打开一次redis的远程连接,消耗资源,解决方法就是使用连接池,连接池中有三个重要的类,分别如下
JedisPoolConfig:设置和读取配置文件
JedisPool:Jedis连接池
Jedis:Jedis操作对象
Jedis 操作 Redis 代码如下
package jedistest;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Jedis 操作 Redis(使用连接池)
*/
public class JedisPoolTest {
private static int MAX_TOTAL = 20; // 最大连接数,默认为8,-1表示不限制
private static int MAX_IDLE = 10; // 最大空闲连接数,默认为8
private static int MIN_IDLE = 5; // 初始化连接数
private static int MAX_WAIT = 10000; // 最大等待时间,单位为毫秒,默认-1,永不超时,如果超时,抛出异常 JedisConnectionException
private static boolean TEST_ON_BORROW = true; // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static String HOST = "192.168.242.161"; // IP
private static int PORT = 6379; // 端口,默认6379
private static String AUTH = "admin"; // redis 密码
private static int TIMEOUT = 1000; // 超时时间
private static Jedis jedis = null;
private JedisPool jedisPool = null;
@Before
public void init() throws Exception {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(MAX_TOTAL);
poolConfig.setMaxIdle(MAX_IDLE);
poolConfig.setMinIdle(MIN_IDLE);
poolConfig.setMaxWaitMillis(MAX_WAIT);
poolConfig.setTestOnBorrow(TEST_ON_BORROW);
// 如果有密码,需要设置
// JedisPool jedisPool = new JedisPool(poolConfig, HOST, PORT, TIMEOUT, AUTH);
jedisPool = new JedisPool(poolConfig, HOST, PORT);
jedis = jedisPool .getResource();
}
// Redis String 字符串
@Test
public void testString() throws Exception {
// set get
jedis.set("address", "HeBei");
System.out.println("address = " + jedis.get("address"));
// append
jedis.append("address", " tangsan");
System.out.println("address = " + jedis.get("address"));
// del
jedis.del("address");
System.out.println("address = " + jedis.get("address"));
}
// Redis List 列表
@Test
public void testList() throws Exception {
// lpush lrange
jedis.lpush("dblist", "mysql", "oracle", "db2");
System.out.println("dblist = " + jedis.lrange("dblist", 0, -1));
// rpush lrange
jedis.rpush("dblist", "mongodb", "redis");
System.out.println("dblist = " + jedis.lrange("dblist", 0, -1));
// lpop lrange
jedis.lpop("dblist");
System.out.println("dblist = " + jedis.lrange("dblist", 0, -1));
// llen
System.out.println(jedis.llen("dblist"));
}
// Redis Set 无序集合
@Test
public void testSet() throws Exception {
// sadd smembers
jedis.sadd("myset", "peach", "pear", "banana");
System.out.println("myset = " + jedis.smembers("myset"));
// srem smembers
jedis.srem("myset", "banana");
System.out.println("myset = " + jedis.smembers("myset"));
// scard
System.out.println(jedis.scard("myset"));
}
// Redis Hash 哈希
@Test
public void testHash() throws Exception {
// hset
Map<String, String> hash = new HashMap<String, String>();
hash.put("name", "tom");
hash.put("age", "20");
hash.put("address", "ShangHai");
jedis.hmset("user", hash);
// hdel
jedis.hdel("user", "address");
// hexists
System.out.println(jedis.hexists("user", "address"));
// hkeys
Set<String> hkeys = jedis.hkeys("user");
for (String str : hkeys) {
System.out.println(str);
}
// hvals
List<String> hvals = jedis.hvals("user");
for (String str : hvals) {
System.out.println(str);
}
// hgetall
Map<String, String> map = jedis.hgetAll("user");
for(Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
// Redis ZSet 有序集合
@Test
public void testZSet() throws Exception {
// zadd zrange
Map<String, Double> scoreMembers = new HashMap<String, Double>();
scoreMembers.put("math", 90.0);
scoreMembers.put("english", 87.5);
scoreMembers.put("sports", 94.0);
scoreMembers.put("music", 67.0);
scoreMembers.put("politics", 97.0);
jedis.zadd("score_set", scoreMembers);
System.out.println(jedis.zrange("score_set", 0, -1));
System.out.println(jedis.zrangeWithScores("score_set", 0, -1));
// zrem
jedis.zrem("score_set", "sports");
System.out.println(jedis.zrange("score_set", 0, -1));
// zcard
System.out.println(jedis.zcard("score_set"));
// zrank
System.out.println(jedis.zrank("score_set", "math"));
}
// Java对象存储到Redis(使用序列化)
@Test
public void testSerialize() throws Exception {
User user = new User(1, "张三", "河北");
jedis.set("user".getBytes(), SerializeUtil.serialize(user));
}
// Redis 反序列化后转为Java对象
@Test
public void testDeSerialize() throws Exception {
byte[] bytes = jedis.get("user".getBytes());
System.out.println((User)SerializeUtil.deSerialize(bytes));
}
// 释放资源
@After
public void destory() throws Exception {
if (jedis != null) {
jedis.close();
}
}
}
User 对象
package jedistest;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User() {
}
public User(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
序列化与反序列化工具类
package jedistest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
/**
* 序列化对象
*/
public static byte[] serialize(Object obj) {
byte[] bytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
;
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
bytes = baos.toByteArray();
baos.close();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
/**
* 反序列化对象
*/
public static Object deSerialize(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
obj = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}