目录
前言
使用 Redis 官方推荐的 Jedis,在 Java 应用中操作 Redis。Jedis 几乎涵盖了 Redis 的所有命令,操作 Redis 的命令在 Jedis 中以方法的形式出现。
▶ Jedis 源码 :https://github.com/xetorthio/jedis
▶ API 文档 :http://xetorthio.github.io/jedis/
▶ 下载 :http://search.maven.org/,搜索 Jedis
一、下载 Jedis 和 Commons-Pool
1、下载 Jedis
Jedis 是 Redis 的 Java 客户端。
Maven 依赖如下
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
2、下载 Commons-Pool
Jedis 对象并不是线程安全的,在多线程下使用同一个 Jedis 对象会出现并发问题。为了避免每次使用 Jedis 对象时都需要重新构建,Jedis 提供了 JedisPool。JedisPool 是基于 Commons Pool 2 实现的一个线程安全的连接池。
Maven 依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
二、字符串
package com.fancy;
import redis.clients.jedis.Jedis;
import java.util.List;
public class RedisString {
public static void main(String[] args) {
// 创建 Jedis 对象, 连接到 Redis , 提供需要的ip 和 port
Jedis jedis = new Jedis("127.0.0.1", 6379);
// 添加字符串
jedis.set("breakfast", "bread");
String mybreak = jedis.get("breakfast");
System.out.println("我的早餐" + mybreak);
jedis.append("breakfast", " and egg");
jedis.mset("lunch", "meet", "dinner", "noodles");
List<String> dinners = jedis.mget("lunch", "dinner");
for (String din : dinners) {
System.out.println("eat : " + din);
}
}
}
三、 哈希
1、使用 Jedis 连接实例池
package com.fancy.utils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtils {
// 定义连接池对象
private static JedisPool pool = null;
// 创建连接池
public static JedisPool open(String host, int port) {
if (pool == null) {
// 使用 JedisPool
JedisPoolConfig config = new JedisPoolConfig();
// 最大的 Jedis 实例数, 连接池中是 Jedis 实例, 默认是 8
config.setMaxTotal(10);
// 最大的实例数, 设置这个可以保留足够的连接, 快速获取到Jedis对象
config.setMaxIdle(3);
// 提前检查 Jedis 对象, 为 true 获取的 Jedis 一定是可用的
config.setTestOnBorrow(true);
// 创建 Jedis 连接池, Redis 没有访问密码时的使用方式
pool = new JedisPool(config, host, port);
// Redis 有访问密码时的使用方式
//pool = new JedisPool(config, host, port, 6 * 1000, "123456");
}
return pool;
}
// 关闭连接池
public static void close() {
if (pool != null) {
pool.close();
}
}
}
2、使用连接池操作 hash 数据类型
@Test
public void test() {
// 创建连接池
JedisPool pool = RedisUtils.open("127.0.0.1", 6379);
Jedis jedis = null;
try {
// 从连接池中获取 Jedis 对象
jedis = pool.getResource();
// 设置 hash 类型.
jedis.hset("loginUser", "username", "zhangsan");
System.out.println("username : " + jedis.hget("loginUser", "username"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
Redis 其他 数据结构 类似于前两者的操作,在此不再一一赘述。