本文主要Java中,连接操作Redis和常用操作使用方法及示例代码,以及相关Redis面试题。

1、Redis的客户端lettuce

Lettuce和Jedis的都是连接Redis Server的客户端程序。Jedis在实现上是直连redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例增加物理连接。Lettuce基于Netty的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例.

2、Lettuce客户端安装引用

1) 下载指定的版本Jar包

下载地址https://github.com/lettuce-io/lettuce-core/releases

2) 在Pom.xml中添加Maven依赖

<dependency>
    <groupId>biz.paluch.redis</groupId>
    <artifactId>lettuce</artifactId>
    <version>3.2.Final</version>
</dependency>

其它版本https://github.com/lettuce-io/lettuce-core/wiki/Download

3、使用Lettuce连接Redis

import com.lambdaworks.redis.*;
public class ConnectToRedis {
  public static void main(String[] args) {
    RedisClient redisClient = new RedisClient(
    RedisURI.create("redis://password@host:port"));//password是连接的密码,不需验证删除password@即可
    RedisConnection<String, String> connection = redisClient.connect();
    System.out.println("Connected to Redis");
    connection.close();
    redisClient.shutdown();
  }
}

使用Spring时,则可以使用Spring XML创建一个实例,内容如下

<bean id="RedisClient" class="com.lambdaworks.redis.support.RedisClientFactoryBean">
    <property name="uri" value="redis://host:port"/>
</bean>

使用代码:

import com.lambdaworks.redis.*;
import org.springframework.beans.factory.annotation.Autowired;
public class MySpringBean {
    private RedisClient redisClient;
    @Autowired
    public void setRedisClient(RedisClient redisClient) {
        this.redisClient = redisClient;
    }
    public String ping() {
        RedisConnection<String, String> connection = redisClient.connect();
        String result = connection.ping();
        connection.close();
        return result;
    }
}

注意:

通常程序退出后,需要使用shutdown方法关闭:

redisClient.shutdown();

如果使用的是SpringCDI,则框架将负责管理资源,而不必使用shutdown方法关闭客户端。

4、使用SSL的Lettuce客户端

为了增加安全性,可以使用SSL连接保护连接的安全。Lettuce本机支持SSL连接。

import com.lambdaworks.redis.*;
public class ConnectToRedisSSL {
public static void main(String[] args) {
RedisClient redisClient = new RedisClient(
RedisURI.create("rediss://password@host:port"));
RedisConnection<String, String> connection = redisClient.connect();
System.out.println("Connected to Redis using SSL");
connection.close();
redisClient.shutdown();
}
}

注意:根据服务器的SSL配置,您可能需要使用keytool实用程序在本地JVM中安装证书。

5、使用Lettuce客户端读写数据(set和get)

一旦连接到Redis,您就可以开始读取和写入数据。下面的代码片段将值bar写入到Redis key foo中,然后读取并打印出来:

import com.lambdaworks.redis.*;
public class ConnectToRedis {
  public static void main(String[] args) {
    RedisClient redisClient = new RedisClient(
      RedisURI.create("redis://password@host:port"));//password是连接的密码,不需验证删除password@即可
    RedisConnection<String, String> connection = redisClient.connect();
    System.out.println("Connected to Redis");
    connection.set("foo", "bar");
    String value = connection.get("foo");
    System.out.println(value);
    connection.close();
    redisClient.shutdown();
  }
}

官方文档https://redislabs.com/lp/redis-java/




推荐文档