概述
最近复习了一下redis底层传输协议,然后抽时间写了一个例子,话不多说,上代码
package com.example.demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* @author lt
* @date 2019-01-15 10:07:21
*/
public class RedisSocket {
public static void main(String[] args) throws IOException {
String host = "127.0.0.1";
int port = 6379;
Socket socket = new Socket(host, port);
socket.setSoTimeout(3000);
// 建立连接后获得IO出流
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
//看过很多是将斜杠转义的写法,是不对的,因为他和r或者n连起来当做命令,而不是单纯的字符串
//redis在处理命令时也做了判断,直接发送redis cli命令也可以解析,但必须以rn或者n结尾
//String message = "*3\r\n$3\r\nSET\r\n$6\r\nsocket\r\n$10\r\nsocketTest\r\n";
getResult(outputStream, inputStream, "*3rn$3rnSETrn$6rnsocketrn$10rnsocketTestrn");
getResult(outputStream, inputStream, "error testrn");
getResult(outputStream, inputStream, "*2rn$3rngetrn$5rnsocketrn");
getResult(outputStream, inputStream, "set socket socketTest1rn");
getResult(outputStream, inputStream, "exists socketrn");
getResult(outputStream, inputStream, "get socketrn");
getResult(outputStream, inputStream, "keys *rn");
getResult(outputStream, inputStream, "get otherTestn");
socket.close();
System.err.println("*****socket closed*****");
}
private static void getResult(OutputStream outputStream, InputStream inputStream, String cmd) throws IOException {
System.err.println("rnsend command : " + cmd.replaceAll("\r\n", " "));
outputStream.write(cmd.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
//此写法是为了测试,不适合返回数据太多的情况
byte[] bytes = new byte[128];
int length = inputStream.read(bytes);
String result = new String(bytes, 0, length, StandardCharsets.UTF_8);
while (result.length() > 0) {
int index = result.indexOf("rn");
//取第一个命令
String currentStr = result.substring(0, index);
//剩余命令,注意:rn占两个长度
result = result.substring(index + 2);
if (currentStr.startsWith("+")) {
System.err.println("+ status reply message:" + currentStr.substring(1));
} else if (currentStr.startsWith("-")) {
System.err.println("- error reply message:" + currentStr.substring(1));
} else if (currentStr.startsWith(":")) {
System.err.println(": integer reply message:" + currentStr.substring(1));
} else if (currentStr.startsWith("$")) {
System.err.println("$ bulk reply message:" + currentStr.substring(1));
} else if (currentStr.startsWith("*")) {
System.err.println("* multi bulk reply message:" + currentStr.substring(1));
}else {
System.err.println("other message : " + currentStr);
}
}
}
}
需要注意的地方看里面注释说明吧,不多说了
redis版本是3.2.100
更详细的请看文档:http://redisdoc.com/topic/protocol.html
http://www.redis.cn/topics/protocol.html
欢迎转载,转载请注明出处,谢谢!!!
最后
以上就是壮观麦片为你收集整理的java 链接redis demo_java socket 连接redis,解析redis协议的全部内容,希望文章能够帮你解决java 链接redis demo_java socket 连接redis,解析redis协议所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复