标签:comm red command nec ringbuf this 服务 -- 消息
redis 底层是c,c++实现的
那java是怎么调用本地方法的呢? JNI 可以通过java调用本地方法 (C,C++实现的),但是是在jvm层才可以使用的
redis的java的客户端:jedis ,Jredis ,ric ,jedisplus , redisclient (首选是 jedis ,因为 jedis 是团队运作,支持 Redis cluster (集群))
分析本质
客户端(java)-------------------------服务端(redis)
opi操作层-------------------------
消息协议层----------------------
传输层---------------------------
代码实现
/**
* api操作层
* @author Lenovo
*
*/
public class Client {
Connection connection;
public Client(String host,int port){
this.connection=new Connection(host, port);
}
public String set(String key,String value){
connection.sendCommand(Protocol.Command.SET,key.getBytes(),value.getBytes());
return connection.getStatusCocdereply();
}
public String get(String key){
connection.sendCommand(Protocol.Command.SET, key.getBytes());
return connection.getStatusCocdereply();
}
}
/**
* 消息协议层
* @author Lenovo
*
*/
public class Protocol {
public static final String DOLLAR_BYTE="$"; // 字符
public static final String ASTERISK_BYTE="*"; //数组
public static final String BLANK_STRINO="\r\n"; // 结束标记
//组装数组
public static void sendCommand(OutputStream os,Command command,byte[]...args){
StringBuffer sb=new StringBuffer();
sb.append(ASTERISK_BYTE).append(args.length-1).append(BLANK_STRINO);
sb.append(DOLLAR_BYTE).append(command.name().length()).append(BLANK_STRINO);
sb.append(command.name()).append(BLANK_STRINO);
for(final byte[] arg:args){
sb.append(DOLLAR_BYTE).append(arg.length).append(BLANK_STRINO);
sb.append(new String(arg)).append(BLANK_STRINO);
}
System.out.println(sb.toString());
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static enum Command{
GET,SET,KEYS
}
}
/**
* 传输层
* @author Lenovo
*
*/
public class Connection {
private Socket socket;
private String host;
private int port;
private OutputStream outputStream;
private InputStream inputStream;
public Connection(String host,int port){
this.host=host;
this.port=port;
}
// todo i/o 复用
public Connection connection(){
try {
//if(!isConnection()){
socket=new Socket(host,port);
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
//}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//发送数据和命令
public Connection sendCommand(Protocol.Command command,byte[] ...args){
connection();
Protocol.sendCommand(outputStream,command,args);
return this;
}
public String getStatusCocdereply(){
byte[] bytes=new byte[1024];
try {
socket.getInputStream().read(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new String(bytes);
}
}
标签:comm red command nec ringbuf this 服务 -- 消息
原文地址:https://www.cnblogs.com/xp0813/p/11285785.html