Java 连接Redis客户端 Jedis
1.首先找到找到 jedis 的jar 包 点击这里
这里我用的是这个
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.1</version>
</dependency>
最简单的测试:
package com.dyl;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.Map;
public class RedisDemo01 {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.set("java","世界上最好的语言");
jedis.set("age","1");
System.out.println(jedis.incrBy("age", 10));
System.out.println(jedis.get("java"));
//hash
jedis.hset("person","name","zhangsan");
Map<String,String> mp = new HashMap<String,String>();
mp.put("age","10");
mp.put("city","Beijing");
jedis.hmset("person",mp);
System.out.println(jedis.hgetAll("person"));
//list
jedis.lpush("list1","1","2","3");
System.out.println(jedis.lrange("list1",0,-1));
//set
jedis.sadd("set1","a","b","c");
System.out.println(jedis.smembers("set1"));
//sortset
Long zadd = jedis.zadd("set2", 1,"zhansgan");
System.out.println(jedis.zrangeWithScores("set2",0,-1));
}
}
输出结果:
11
世界上最好的语言
{name=zhangsan, city=Beijing, age=10}
[3, 2, 1, hash1, hash1, b, bb, d, e, f, a, 1, 2, 3]
[b, c, a]
[[zhansgan,1.0]]
通过连接池获取连接
package com.dyl;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Redisdemo02 {
public static void main(String[] args) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
JedisPool jedisPool = new JedisPool("127.0.0.1",6379);
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
System.out.println(jedis.get("java"));
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
if (jedis==null){
jedis.close();
}
}
}
}
运行结果
世界上最好的语言
Pipeline //批量
package com.dyl;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class RedisDemo03 {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
Set<String> keys1 = jedis.keys("*");
for(String k:keys1){
System.out.println(k);
}
System.out.println("================");
List<String> keys = new ArrayList<String>() {//这个大括号 就相当于我们 new 接口
{//这个大括号 就是 构造代码块 会在构造函数前 调用
add("xx");
add("a");
}
};
Pipeline pipeline = jedis.pipelined();
for (String key:keys){
pipeline.del(key);
}
pipeline.sync();
keys1 = jedis.keys("*");
for(String k:keys1){
System.out.println(k);
}
}
}
a
b
set
c
hash1
d
set2
e
list
rank1
ranks
person
str1
str2
listKey
rank
set1
key
age
================
b
set
c
hash1
d
set2
e
list
rank1
ranks
person
str1
str2
listKey
rank
set1
key
age