Redis学习:Java连接Redis服务端

1. 修改 Redis 配置文件 redis.conf

  在 redis 的安装目录中,将 redis.conf 复制到 /etc/ 目录下。

  在 Redis 的配置文件 redis.conf 中设置了 bind 127.0.0.1, 即表明只有主机才可访问,将其注释掉即可。 vi /etc/redis.conf

  然后需要关闭保护模式,redis 处于保护模式时,只能本地连接,所以将 protected-mode yes 改成 no

  然后修改防火墙配置 vi /etc/sysconfig/iptables   ,将 redis 端口添加进去。

  然后重启 Redis 服务。

 

2. Java

导入连接 redis 所需的包

编写代码,输出信息则连接成功

    @Test
    public void testJedisConnect() {
//        连接 redis 服务器
        Jedis jedis = new Jedis("192.168.230.4",6379);
//        测试 redis 服务器是否在运行
        System.out.println(jedis.ping());
        System.out.println(jedis.info());
}</span></pre>

 

测试获取 key-value

    /**
     * 获取 set,hash,sortedset 这三种数据类型对应的 key-value
     */
    @Test
    public void getKeyValue() {
//        连接 redis 服务器
        Jedis jedis = new Jedis("192.168.230.4",6379);
        Set<String> keys = jedis.keys("*");

// 判断 key 的类型
for (String key : keys) {
String type
= jedis.type(key);

        </span><span style="color: rgba(0, 0, 255, 1)">if</span>("set"<span style="color: rgba(0, 0, 0, 1)">.equals(type)) {
            Set</span>&lt;String&gt; smembers =<span style="color: rgba(0, 0, 0, 1)"> jedis.smembers(key);
            System.out.println(</span>"set类型:"<span style="color: rgba(0, 0, 0, 1)">);
            </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (String value : smembers) {
                System.out.println(value);
            }
            System.out.println(</span>"-----------------------"<span style="color: rgba(0, 0, 0, 1)">);
        }</span><span style="color: rgba(0, 0, 255, 1)">else</span> <span style="color: rgba(0, 0, 255, 1)">if</span>("hash"<span style="color: rgba(0, 0, 0, 1)">.equals(type)) {
            System.out.println(</span>"map类型:"<span style="color: rgba(0, 0, 0, 1)">);
            Map</span>&lt;String, String&gt; map =<span style="color: rgba(0, 0, 0, 1)"> jedis.hgetAll(key);
            </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (String strkey : map.keySet()) {
                System.out.println(map.get(strkey));
            }
            System.out.println(</span>"-----------------------"<span style="color: rgba(0, 0, 0, 1)">);
        }</span><span style="color: rgba(0, 0, 255, 1)">else</span> <span style="color: rgba(0, 0, 255, 1)">if</span>("zset"<span style="color: rgba(0, 0, 0, 1)">.equals(type)) {
            System.out.println(</span>"sorted类型:"<span style="color: rgba(0, 0, 0, 1)">);
            Set</span>&lt;Tuple&gt; zset = jedis.zrangeWithScores(key, 0, -1<span style="color: rgba(0, 0, 0, 1)">);
            </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (Tuple string : zset) {
                System.out.println(string);
            }
            System.out.println(</span>"-----------------------"<span style="color: rgba(0, 0, 0, 1)">);
        }    
    }
    jedis.close();
}
</span></pre>