Source resolve redis

redis bottom is c, c ++ implementation

That is how java native method call it? JNI can call native methods (C, C ++ implementation) java, but that can only be used in jvm layer

 

redis the java client: jedis, Jredis, ric, jedisplus, redisclient (jedis is preferred, because jedis a team operation, support Redis cluster (cluster))

 

Analysis of the essence

  The client (java) ------------------------- server (redis)

    opi operational layer -------------------------

    Protocol layer message ----------------------

    --------------------------- transport layer

 

Code

/**
* 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
}

}

/ **
* transporting layer
* @author the 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);
}
}

Guess you like

Origin www.cnblogs.com/xp0813/p/11285785.html