1、Jedis
1、如何使用
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
@Test
public void testJedis() {
// 1.连接 redis, 默认就是 localhost:6379
Jedis jedis = new Jedis("127.0.0.1", 6379);
// 2.操作 redis
jedis.set("name", "zzw");
String name = jedis.get("name");
System.out.println(name);
// 3.关闭连接
jedis.close();
}
2、读写 Redis 数据
@Test
public void testList() {
// 1.连接 redis
Jedis jedis = new Jedis("127.0.0.1", 6379);
// 2.操作 redis
jedis.lpush("list1", "a", "b", "c");
jedis.rpush("list1", "x", "y", "z");
List<String> list1 = jedis.lrange("list1", 0, -1);
list1.forEach(System.out::println);
// 3.关闭连接
jedis.close();
}
@Test
public void testHash() {
// 1.连接 redis
Jedis jedis = new Jedis("127.0.0.1", 6379);
// 2.操作 redis
jedis.hset("hash1", "name", "zhangsan");
jedis.hset("hash1", "age", "18");
Map<String, String> map = jedis.hgetAll("hash1");
map.forEach((key, value) -> System.out.println(key + ": " + value));
// 3.关闭连接
jedis.close();
}
3、Jedis 简易工具类开发
# redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.maxTotal=30
redis.maxIdle=10
import java.util.ResourceBundle; // 资源包
public class JedisUtil {
private static final JedisPool jp; // 连接池
private static final String host;
private static final int port;
private static final int maxTotal;
private static final int maxIdle;
static {
ResourceBundle rb = ResourceBundle.getBundle("redis"); // 资源包
host = rb.getString("redis.host");
port = Integer.parseInt(rb.getString("redis.port"));
maxTotal = Integer.parseInt(rb.getString("redis.maxTotal"));
maxIdle = Integer.parseInt(rb.getString("redis.maxIdle"));
JedisPoolConfig config = new JedisPoolConfig(); // 连接池配置
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
jp = new JedisPool(config, host, port);
}
public static Jedis getJedis() {
return jp.getResource();
}
}
本文来自博客园,作者:lidongdongdong~,转载请注明原文链接:https://www.cnblogs.com/lidong422339/p/17790783.html

浙公网安备 33010602011771号