• 【入门篇】1.3 redis客户端之 jedis 高级使用示例



    在这里插入图片描述

    0.前言

    Jedis是Redis的Java客户端,它支持所有的Redis原生命令,使用方便,且可以与Java项目无缝集成。 该库的最新版本支持Redis 5.0、6.0、6.2、7.0和7.2。
    最新依赖

    <dependency>
        <groupId>redis.clientsgroupId>
        <artifactId>jedisartifactId>
        <version>5.0.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    有关Jedis版本与Redis版本和JDK的兼容性的信息:

    Jedis版本支持的Redis版本JDK兼容性
    3.9+5.0和6.2系列8, 11
    >= 4.05.0至当前版本8, 11, 17
    >= 5.06.0至当前版本8, 11, 17

    具体和最准确的信息建议参考官方Jedis文档。

    1. 发布和订阅消息

    这是一种典型的发布/订阅模式,Jedis提供了subscribe方法和publish方法来实现。在这个例子中,我们首先创建了一个Jedis对象和一个消息监听器,然后通过subscribe方法订阅了一个频道,之后在这个频道上通过publish方法发布了一条消息,消息监听器接收到消息后会打印出消息内容和频道名。如果不再需要订阅该频道,可以通过unsubscribe方法来取消订阅。最后,记得关闭Jedis对象来释放资源。

    // 创建Jedis对象
    Jedis jedis = new Jedis("localhost", 6379);
    
    // 创建消息监听器
    JedisPubSub jedisPubSub = new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
            System.out.println("Received message: " + message + " from channel: " + channel);
        }
    };
    
    // 订阅频道
    jedis.subscribe(jedisPubSub, "channel");
    
    // 发布消息
    jedis.publish("channel", "Hello Redis!");
    
    // 取消订阅
    jedisPubSub.unsubscribe("channel");
    
    // 关闭连接
    jedis.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2. 事务操作

    Jedis也支持Redis的事务操作,可以通过multi方法开启一个事务,然后在事务中进行一系列的操作,最后通过exec方法提交事务,如果需要放弃事务,可以使用discard方法。在这个例子中,我们在一个事务中进行了两次set操作,然后提交了事务。

    // 创建Jedis对象
    Jedis jedis = new Jedis("localhost", 6379);
    
    // 开启事务
    Transaction transaction = jedis.multi();
    
    // 执行事务操作
    transaction.set("key1", "value1");
    transaction.set("key2", "value2");
    
    // 提交事务
    transaction.exec();
    
    // 关闭连接
    jedis.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    3. 管道操作

    管道是一种可以一次性发送多个命令到服务器的方式,服务器会一次性返回所有命令的结果,这样可以大大提高效率。在这个例子中,我们使用了Jedis的pipelined方法创建了一个管道对象,然后在管道中执行了三次get命令,通过sync方法提交了管道,然后通过Response对象获取了命令的返回结果。

    // 创建Jedis对象
    Jedis jedis = new Jedis("localhost", 6379);
    
    // 创建管道对象
    Pipeline pipelined = jedis.pipelined();
    
    // 批量执行命令
    Response<String> response1 = pipelined.get("key1");
    Response<String> response2 = pipelined.get("key2");
    Response<String> response3 = pipelined.get("key3");
    
    // 提交命令
    pipelined.sync();
    
    // 获取命令结果
    String value1 = response1.get();
    String value2 = response2.get();
    String value3 = response3.get();
    
    // 关闭连接
    jedis.close();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    4. jedis 支持哨兵模式

    在使用Jedis的哨兵模式之前,你需要先配置好Redis的哨兵模式。这需要至少3个Redis实例,一个作为主节点(master),两个作为从节点(slave)。然后在每个Redis实例上运行一个哨兵进程。

    Redis Sentinel哨兵配置

    1. 主节点配置文件 redis.conf 示例:

      bind 127.0.0.1
      port 6379
      
      • 1
      • 2
    2. 从节点配置文件 redis-slave.conf 示例:

      bind 127.0.0.1
      port 6380
      slaveof 127.0.0.1 6379
      
      • 1
      • 2
      • 3
    3. 哨兵配置文件 sentinel.conf 示例:

      sentinel monitor mymaster 127.0.0.1 6379 2
      sentinel down-after-milliseconds mymaster 60000
      sentinel failover-timeout mymaster 180000
      
      • 1
      • 2
      • 3
      • sentinel monitor mymaster 127.0.0.1 6379 2 表示哨兵监控的主节点名称叫mymaster,地址127.0.0.1,端口6379,2表示至少需要2个哨兵同意才确认主节点挂掉。
      • sentinel down-after-milliseconds mymaster 60000 表示如果60秒内master节点无响应,那么哨兵将master节点标记为主观下线(subjectively down)。
      • sentinel failover-timeout mymaster 180000 表示如果180秒内master节点还是无响应,那么开始进行故障转移。

    使用Jedis连接Redis Sentinel

    1. 引入Jedis依赖。在pom.xml中添加:

      <dependency>
          <groupId>redis.clientsgroupId>
          <artifactId>jedisartifactId>
          <version>3.7.0version>
      dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
    2. Java代码:

      Set<String> sentinels = new HashSet<String>();
      sentinels.add("127.0.0.1:26379"); //添加哨兵地址
      JedisSentinelPool sentinelPool = new JedisSentinelPool("mymaster", sentinels); //创建JedisSentinelPool,mymaster是在哨兵配置中定义的主节点名称
      Jedis jedis = null;
      try {
          jedis = sentinelPool.getResource(); //获取Jedis对象
          jedis.set("key", "value");  //进行Redis操作
          String value = jedis.get("key");
          System.out.println(value);
      } finally {
          if (jedis != null) {
              jedis.close();  //关闭连接
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14

    Jedis会自动处理故障转移,无需我们手动切换。当Redis主节点出现故障,哨兵会自动选举新的主节点,Jedis也会自动连接到新的主节点。

    5. jedis 支持集群模式

    在使用Jedis的集群模式之前,你需要先配置好Redis的集群模式。这需要至少6个Redis实例,其中3个作为主节点,3个作为从节点。每个主节点都有一个对应的从节点。

    Redis Cluster集群配置

    1. 主节点配置文件 redis-7000.conf 示例:

      port 7000
      cluster-enabled yes
      cluster-config-file nodes-7000.conf
      cluster-node-timeout 5000
      appendonly yes
      
      • 1
      • 2
      • 3
      • 4
      • 5
    2. 从节点配置文件 redis-7001.conf 示例:

      port 7001
      cluster-enabled yes
      cluster-config-file nodes-7001.conf
      cluster-node-timeout 5000
      appendonly yes
      
      • 1
      • 2
      • 3
      • 4
      • 5

    通过Redis自带的redis-cli工具创建集群:

    redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1
    
    • 1

    使用Jedis连接Redis Cluster

    1. 引入Jedis依赖。在pom.xml中添加:

      <dependency>
          <groupId>redis.clientsgroupId>
          <artifactId>jedisartifactId>
          <version>3.7.0version>
      dependency>
      
      • 1
      • 2
      • 3
      • 4
      • 5
    2. Java代码:
      以下是一个使用Jedis连接Redis Cluster的完整Java代码示例:

    import redis.clients.jedis.HostAndPort;
    import redis.clients.jedis.JedisCluster;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class JedisClusterExample {
        public static void main(String[] args) {
            // 创建集群节点集合
            Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
    
            // 向集合中添加新的节点
            jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7000));
            jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7001));
            jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7002));
            jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7003));
            jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7004));
            jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7005));
    
            // 创建JedisCluster对象
            JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes);
    
            try {
                // 保存数据
                jedisCluster.set ("myKey", "Hello, JedisCluster!");
                // 获取数据
                String value = jedisCluster.get("myKey");
                System.out.println("Value stored in Redis : " + value);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedisCluster != null) {
                    try {
                        // 关闭JedisCluster对象
                        jedisCluster.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    5. 参考链接

    https://github.com/redis/jedis/wiki/Getting-started

  • 相关阅读:
    在ubuntu中恢复误删除的文件
    node版本问题
    SpringCloud-4.服务网关(GateWay)
    Docker Buildx使用教程:使用Buildx构建多平台镜像
    面对数据增量同步需求,怎样保障准确性和及时性?
    itext生成pdf
    0xc0000142修复解决方法
    vue相关面试题:Vuex是什么?
    MindFusion JS Chart 2.0 Crack
    Field extension
  • 原文地址:https://blog.csdn.net/wangshuai6707/article/details/134441221