慕课网-一站式学习Redis从入门到高可用分布式实践-第3章-Redis客户端的使用-Java客服端:jedis
Java客服端:Jedis
1.Jedis 是什么
2.Maven依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
3.Jedis 直连
1)生成一个Jedis对象,这个对象负责和指定Redis节点进行通信
Jedis jedis = new Jedis("127.0.0.1", 6379);
2)jedis 执行 set 操作
jedis.set("hello", "world");
3)jedis 执行 get 操作,value=“world”
String value = jedis.get("hello");
Jedis 格式
Jedis(String host, int port, int connectionTimeout, int soTimeout)
host:Redis 节点的所在机器的 IP
port:Redis 节点的端口
connectionTimeout:客户端连接超时
soTimeout:客户端读写超时
4.简单使用
// 1.string
// 输出结果:OK
jedis.set("hello", "world");
//输出结果:world
jedis.get("hello");
// 输出结果:1
jedis.incr("counter");
// 2.hash
jedis.hset("myhash', "f1", "v1");
jedis.hset("myhash', "f2", "v2");
// 输出结果:{f1=v1, f2=v2}
jedis.hgetAll("myhash");
// 3.list
jedis.rpush("mylist", "1");
jedis.rpush("mylist", "2");
jedis.rpush("mylist", "3");
// 输出结果:[1,2,3]
jedis.lrange("mylist", 0, -1)
// 4.set
jedis.sadd("myset", "a");
jedis.sadd("myset", "b");
jedis.sadd("myset", "c");
// 输出结果:[b, a]
jedis.smembers("myset")
//zset
jedis.zadd("myzset", 99, "tom");
jedis.zadd("myzset", 66, "peter");
jedis.zadd("myzset", 33, "james");
// 输出结果:[[["james"], 33.0], [["peter"], 66.0], [["tom"], 99.0]]
jedis.zrangeWithScores("myzset", 0, -1);
5.Jedis 直连

6.Jedis 连接池

6.方案对比

7.简单使用
// 初始化 Jedis 连接池,通常来讲 JedisPool 是单例的。
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
JedisPool jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379);
Jedis jedis = null;
try {
// 1.从连接池获取 jedis 对象
jedis = jedisPool.getResource();
// 2.执行操作
jedis.set("hello", "world");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
//如果使用JedisPool,close 操作不是关闭连接,代表归还连接池
jedis.close();
}
posted on 2019-11-25 12:33 herisson_pan 阅读(14) 评论(0) 收藏 举报
浙公网安备 33010602011771号