最近实现了基于netty4的beanstalkd的客户端, 实现此客户端的目的是为了学习netty。
beanstalkd是一个高性能、轻量级的分布式内存队列系统,个人认为,如果需要一个轻量型的 中间件, beanstalkd是很不错的一个选择,协议也很简单。beanstalkd的详细介绍 可见点击打开链接。
针对消息中间件的概念,分为消息的提供者和消息的消费者,结合beanstalkd和netty的概念,beanstalkd中tube与netty中的channel一一对应。为了在同一个项目中消息的提供者与消息的消费者不相互影响,相同名称的tube,提供者和消费者使用不同的channel。
1. beanstalk协议的封装
协议的封装参考了dinstone,首先定义接口表示协议的功能
package com.haole.mq.beanstalk.command;
import io.netty.buffer.ByteBuf;
import java.nio.charset.Charset;
/**
* Created by shengjunzhao on 2017/5/27.
*/
public interface Command {
String getCommandLine(); // 拼接协议的命令
ByteBuf prepareRequest(ByteBuf sendBuf, Charset charset, String delimiter); // 编码命令到ByteBuf中
}
package com.haole.mq.beanstalk.command;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import java.nio.charset.Charset;
/**
* Created by shengjunzhao on 2017/5/27.
*/
public class AbstractCommand implements Command {
private String commandLine;
@Override
public String getCommandLine() {
return this.commandLine;
}
@Override
public ByteBuf prepareRequest(ByteBuf sendBuf,Charset charset, String delimiter) {
sendBuf.writeBytes(this.commandLine.getBytes(charset));
sendBuf.writeBytes(delimiter.getBytes(charset));
return sendBuf;
}
public void setCommandLine(String commandLine) {
this.commandLine = commandLine;
}
}
beanstalkd每一个协议对于一个具体的类,例如:put命令实现类
package com.haole.mq.beanstalk.command;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
/**
* put command
* Created by shengjunzhao on 2017/5/27.
*/
public class PutCommand extends AbstractCommand {
private final static Logger log = LoggerFactory.getLogger(PutCommand.class);
private byte[] data;
public PutCommand(int priority, int delay, int ttr, byte[] data) {
if (data == null) {
throw new IllegalArgumentException("data is null");
}
if (data.length > 65536) {
throw new IllegalArgumentException("data is too long than 65536");
}
setCommandLine("put " + priority + " " + delay + " " + ttr + " " +