redission作为redis 官方推荐的java客户端。 redission使用netty4.x作为网络层。 redission使用异步io方式操作。这与jedis 同步io操作方式完全不同。
但是redission也提供了同步操作方式。
在org.redisson.client 包下面,RedisClient 提供了对netty client端的包装。RedisClient 提供了同步或者异步连接redis服务器的方式,同时也提供了断线重连的机制。
ConnectionWatchdog 过滤器实现了断线重连的机制。
在redission中也提供了编码和解码器。
RedisClient 使用ChannelGroup来管理实际的socketchannel链接。
在netty中,实际输入输出操作都是通过Channel通道来进行。虽然,netty和apache mina架构非常类似,这也加快了使用apache mina的人迁移到netty上面。
但是在netty 中使用Channel 管理输入输出流。在apache mina 是使用IoSession来管理输入输出流。
RedisClient 代码注释如下:
//redisclient use netty4.x
public class RedisClient {
//构造客户端
private final Bootstrap bootstrap;
//连接地址
private final InetSocketAddress addr;
//管理客户端
private final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
private final long timeout;
public RedisClient(String host, int port) {
this(new NioEventLoopGroup(), NioSocketChannel.class, host, port, 60*1000);
}
public RedisClient(EventLoopGroup group, Class<? extends SocketChannel> socketChannelClass, String host, int port, int timeout) {
//连接端口
addr = new InetSocketAddress(host, port);
//构造客户端
bootstrap = new Bootstrap().channel(socketChannelClass).group(group).remoteAddress(addr);
//配置业务处理。这里实现了断线重连机制和编码解码功能
bootstrap.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addFirst(new ConnectionWatchdog(bootstrap, channels),
new CommandEncoder(),
new CommandsListEncoder(),
new CommandsQueue(),
new CommandDecoder());
}
});
//设置链接超时时间
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
this.timeout = timeout;
}
public InetSocketAddress getAddr() {
return addr;
}
long getTimeout() {
return timeout;
}
public Bootstrap getBootstrap() {