根据 Redis 的 RESP 协议,我们可以看出,SOCKET 在给 Redis 服务器发送数据需要遵循如下格式:
*3$3SET$4test$6123456
那么我们可以利用 SOCKET 来自己实现一套 Redis 客户端
RESP 协议类
public class Resp {public static final String START = "*";public static final String STR_LENGTH = "$";public static final String LINE = "\r\n";public enum command {SET, GET, INCR}}
RedisClient Socket
public class MyJedisSocket {private Socket socket;private InputStream inputStream;private OutputStream outputStream;public MyJedisSocket(String host, int port) {try {socket = new Socket(host, port);inputStream = socket.getInputStream();outputStream = socket.getOutputStream();} catch (IOException e) {e.printStackTrace();}}// 向 Redis 服务器发送数据public void send(String str) {try {outputStream.write(str.getBytes());} catch (IOException e) {e.printStackTrace();}}// 读取 Redis 服务器端返回的数据public String read() {byte[] buffer = new byte[1024];int count = 0;try {count = inputStream.read(buffer);} catch (IOException e) {e.printStackTrace();}return new String(buffer, 0, count, StandardCharsets.UTF_8);}}
Redis Client 类
public class MyJedis {private MyJedisSocket myJedisSocket;public MyJedis(String host, int port) {myJedisSocket = new MyJedisSocket(host, port);}public String set(String key, String value) {myJedisSocket.send(covert(Resp.command.SET, key, value));return myJedisSocket.read();}public String get(String key) {myJedisSocket.send(covert(Resp.command.GET, key));return myJedisSocket.read();}public String incr(String key) {myJedisSocket.send(covert(Resp.command.INCR, key));return myJedisSocket.read();}public static String covert(Resp.command command, String... strings) {StringBuilder sb = new StringBuilder();sb.append(Resp.START).append(1 + strings.length).append(Resp.LINE);sb.append(Resp.STR_LENGTH).append(command.toString().length()).append(Resp.LINE);sb.append(command.name()).append(Resp.LINE);for (String str : strings) {sb.append(Resp.STR_LENGTH).append(str.length()).append(Resp.LINE);sb.append(str).append(Resp.LINE);}return sb.toString();}public static void main(String[] args) {MyJedis jedis = new MyJedis("127.0.0.1", 6379);System.out.println(jedis.set("test", "123456"));System.out.println(jedis.get("test"));System.out.println(jedis.incr("lock"));}}
