之前的日报中有关于jedis和jediscluster对数据的操作
https://blog.youkuaiyun.com/qq_42337039/article/details/113737777
1. jedis连接redis单机
1.1 引入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
建立测试工程
public class jedisTest{
@Test
public void testJedis() throws Exception{
Jedis jedis = new Jedis("192.168.241.133",6379);
jedis.set("test","my forst jedis");
String str = jedis.get("test");
System.out.println(str);
jedis.close();
}
}
这种方式每次连接都要创建一个新的连接,执行完后就会关闭,非常浪费资源,所以使用jedispool连接
2.jedisPool连接redis
@Test
public void testJedisPool()throws Exception{
//创建连接池对象
JedisPool jedispool = new JedisPool("192.168.241.133",6379);
//从连接池中获取一个连接
Jedis jedis = jedispool.getResource();
//使用jedis操作redis
jedis.set("test", "my forst jedis");
String str = jedis.get("test");
System.out.println(str);
//使用完毕 ,关闭连接,连接池回收资源
jedis.close();
//关闭连接池
jedispool.close();
}
3.jediscluster连接redis
jediscluster专门用来连接redis集群
@Test
public void testJedisCluster()throws Exception{
//创建jedisCluster对象,有一个参数 nodes是Set类型,Set包含若干个HostAndPort对象
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.241.133",7001));
nodes.add(new HostAndPort("192.168.241.133",7002));
nodes.add(new HostAndPort("192.168.241.133",7003));
nodes.add(new HostAndPort("192.168.241.133",7004));
nodes.add(new HostAndPort("192.168.241.133",7005));
nodes.add(new HostAndPort("192.168.241.133",7006));
JedisCluster jedisCluster = new JedisCluster(nodes);
//使用jedisCluster操作redis
jedisCluster.set("test", "my forst jedis");
String str = jedisCluster.get("test");
System.out.println(str);
//关闭连接池
jedisCluster.close();
}
4.jedisCluster优化-管道(PipeLine)模式支持
参考:https://blog.youkuaiyun.com/youaremoon/article/details/51751991
普遍情况下redisclient和server之间采用的是请求应答的模式,即
Client: command1
Server: response1
Client: command2
Server: response2
…
这种情况下,完成的命令越多交互的次数越多
但是在管道模式下只要进行两次交互
Client: command1,command2…
Server: response1,response2…
集群的特性却导致无法使用管道模式
1、集群将空间分拆为16384个槽位(slot),每一个节点负责其中一些槽位。迁移时对整个slot迁移
2、节点添加,或宕机或不可达的情况下可以正常使用
3、不存在中心或者代理节点, 每个节点中都包含集群所有的节点信息
4、集群中的节点不会代理请求:即如果client将命令发送到错误的节点上,操作会失败,但会返回”-MOVED”或”-ASK”,供client进行永久或临时的节点切换
pipeline模式下命令将被缓存到对应的连接(OutputStream)上,而在真正向服务端发送数据时,节点可能发生了改变,数据就可能发向了错误的节点,这导致批量操作失败
公司项目中用到的pipeline可以去看gprp_util(仅对我个人)