话不多说,有必要先了解以下两点:
- Socket编程
参考: https://www.cnblogs.com/wangcq/p/3520400.html - Redis服务端与客户端之间的通信协议:RESP
参考:https://www.jianshu.com/p/c0c18f9f5494
一切尽在代码中
package com.itdr.demo;
import java.io.IOException;
import java.net.Socket;
public class RedisClientDemo {
private Socket socket;
public RedisClientDemo(String host, int port) throws IOException {
this.socket = new Socket(host, port);
}
private String set(String key, String value) throws IOException {
StringBuilder request = new StringBuilder();
request.append("*3").append("\r\n");
request.append("$3").append("\r\n");
request.append("SET").append("\r\n");
request.append("$").append(key.getBytes().length).append("\r\n");
request.append(key).append("\r\n");
request.append("$").append(value.getBytes().length).append("\r\n");
request.append(value).append("\r\n");
String sendContent = request.toString();
System.out.println("发送到服务器的内容:\n"+sendContent);
socket.getOutputStream().write(sendContent.getBytes());
byte[] response = new byte[1024];
socket.getInputStream().read(response);
return new String(response);
}
private String get(String key) throws IOException {
StringBuilder request = new StringBuilder();
request.append("*2").append("\r\n");
request.append("$3").append("\r\n");
request.append("GET").append("\r\n");
request.append("$").append(key.getBytes().length).append("\r\n");
request.append(key).append("\r\n");
String sendContent = request.toString();
socket.getOutputStream().write(sendContent.getBytes());
byte[] response = new byte[1024];
socket.getInputStream().read(response);
return new String(response);
}
public static void main(String[] args) throws Exception {
RedisClientDemo redis = new RedisClientDemo("你的服务器IP", 6379);
String res = redis.set("key_1","value_1");
System.out.println(res);
String val = redis.get("key_1");
System.out.println(val);
}
}
结果截图
![不可描述](https://i-blog.csdnimg.cn/blog_migrate/bd12d3640bac4137598872198fff1297.png)
思路 / 步骤:
- 通过Socket建立网络上两个进程之间的通信,也就是redis服务端与客户端
- 打开Socket的输入输出流
- 按照redis通信协议RESP来进行读写操作
- 最后需要使用close()方法关闭Socket(Jedis的close()方法是把它还给连接池),这里就不再写
- 结束