Jedis API简单测试

安装Redis

在一台崭新安装的虚拟机上,安装Redis

Prerequsite

  • gcc
  • wget

步骤

apt update
apt install gcc

下载安装包,参考官网:
https://redis.io/download

在这里插入图片描述

Java客户端连接Redis服务器

我使用spring boot将Redis连接设置为一个单例对象,当然在普通Java项目中也是一样的。
加载Jedis依赖包,使用maven:

  <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.0.1</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

最新版参考:Github地址

设置基础设置Bean:

下面有非常多的注释,不进一步解释

@Configuration
public class RedisConnection{
    Logger logger= LoggerFactory.getLogger(RedisConnection.class);

    //设置Bean声明周期类型为单例
    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
    public Jedis getJedis(){
        logger.info("Connecting Redis Server:");
        //连接远程端口
        Jedis jedis=new Jedis("10.0.7.166",6379);
        //这里很奇怪,明明连接上了,返回确实false不用管他。
        if(jedis.isConnected()){
            logger.info("Redis is Connected");
        }
        logger.info(jedis.isConnected()+"");
        return jedis;
    }


}

实际上已经连接上了,接下来测试一些API,还是依靠注释来解释代码:

@Component
public class JedisDataStructureTest implements CommandLineRunner {

      Logger logger=LoggerFactory.getLogger(JedisDataStructureTest.class);
       @Autowired
      private Jedis jedis;

      //ordinary key
      public void ordinaryKey(){
          //测试普通键值
          jedis.set("oneslide","icywater");
          logger.info("get key <oneslide:"+jedis.get("oneslide")+">");
      }

     //list

      public void listRelated(){
         //向list型键cuixuan添加多个字符串
          jedis.lpush("cuixuan","tui","xuan","cui","xuan");
          //输出其长度
          logger.info("listLength:"+jedis.llen("cuixuan"));
          //输出其内容,0 -1代表从头至尾
          logger.info("the list content:");
          logger.info(jedis.lrange("cuixuan",0,-1).toString());
           //弹出一些元素
          logger.info("pop out some element in list");
          for (int i = 0; i < jedis.llen("cuixuan")-2; i++) {
              logger.info(jedis.lpop("cuixuan"));
          }
          logger.info("there are leaved:"+jedis.lrange("cuixuan",0,-1).toString());
      }


      //set
      public void setRelated(){
         //向set中添加值
          jedis.sadd("myset","1","2","3");
          //输出所有成员
          logger.info("myset:"+jedis.smembers("myset").toString());
          logger.info("is 4 exist? "+jedis.sismember("myset","4"));

      }

      //hash set
      public void hashSetRelated(){
          //hash表中添加键值对
          Map<String,String> map=new HashMap<>(5);
          map.put("外形","帅");
          map.put("才华","横溢");
          map.put("婚姻","未婚");
          //将hash表中内容写入Redis
          jedis.hset("oneslide",map);
          logger.info("get key from oneslide HashSet");
          logger.info(jedis.hgetAll("oneslide").toString());



      }
     //sorted set
     public void sortedSetRelated(){
        //用我同事名字写的,随机排名
         List<String> list=new ArrayList<>();
         list.add("崔xx");
         list.add("徐xx");
         list.add("oneslide");
         list.add("鲍xx");
         list.add("梁xx");

         for (int i = 0; i < 5; i++) {
              //mock data
              jedis.zadd("dashboard",Math.random()*10,list.get(i));
         }
         //查看其中一个人的名次
         logger.info("ranking of oneslide in dashboard:"+jedis.zrank("dashboard","oneslide"));
         logger.info("total ranking:");
         //所有人的名次
         logger.info(jedis.zrangeByScore("dashboard",0,10).toString());
     }



    @Override
    public void run(String... args) throws Exception {
        logger.info(jedis.toString());
        //this.ordinaryKey();
        //this.listRelated();
         //this.setRelated();
        //this.hashSetRelated();
        this.sortedSetRelated();
      }
}

正确配置Redis

默认情况下,Redis只接受环回地址连接。也就是说只能在本机redis-cli来测试Redis,
不过可以配置为远程:
简单方法:
Redis is running in protected mode because protected mode is enabled,
no bind address was specified, no authentication password is requested to clients.
In this mode connections are only accepted from the loopback interface.
If you want to connect from external computers to Redis you may adopt one of the following solutions:

  1. Just disable protected mode sending the command ‘CONFIG SET protected-mode no’ from the loopback interface

    redis-cli下操作

    by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent.

  2. Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to ‘no’, and then restarting the server.

  3. If you started the server manually just for testing, restart it with the ‘–protected-mode no’ option.

  4. Setup a bind address or an authentication password.
    NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.

我用的是官网上推荐的方法:
https://redis.io/topics/quickstart

将配置文件/etc/redis/6379.confprotected-mode设置为no,剩下的按照官方文档来。
或者更加简单的方法:
把bind xxxx和protect-mode全部注释掉,然后使用src/redis-server redis.conf来启动。

JavaDoc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值