根据 Redis 的 RESP 协议,我们可以看出,SOCKET 在给 Redis 服务器发送数据需要遵循如下格式:

  1. *3
  2. $3
  3. SET
  4. $4
  5. test
  6. $6
  7. 123456

那么我们可以利用 SOCKET 来自己实现一套 Redis 客户端

RESP 协议类

  1. public class Resp {
  2. public static final String START = "*";
  3. public static final String STR_LENGTH = "$";
  4. public static final String LINE = "\r\n";
  5. public enum command {
  6. SET, GET, INCR
  7. }
  8. }

RedisClient Socket

  1. public class MyJedisSocket {
  2. private Socket socket;
  3. private InputStream inputStream;
  4. private OutputStream outputStream;
  5. public MyJedisSocket(String host, int port) {
  6. try {
  7. socket = new Socket(host, port);
  8. inputStream = socket.getInputStream();
  9. outputStream = socket.getOutputStream();
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. // 向 Redis 服务器发送数据
  15. public void send(String str) {
  16. try {
  17. outputStream.write(str.getBytes());
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. // 读取 Redis 服务器端返回的数据
  23. public String read() {
  24. byte[] buffer = new byte[1024];
  25. int count = 0;
  26. try {
  27. count = inputStream.read(buffer);
  28. } catch (IOException e) {
  29. e.printStackTrace();
  30. }
  31. return new String(buffer, 0, count, StandardCharsets.UTF_8);
  32. }
  33. }

Redis Client 类

  1. public class MyJedis {
  2. private MyJedisSocket myJedisSocket;
  3. public MyJedis(String host, int port) {
  4. myJedisSocket = new MyJedisSocket(host, port);
  5. }
  6. public String set(String key, String value) {
  7. myJedisSocket.send(covert(Resp.command.SET, key, value));
  8. return myJedisSocket.read();
  9. }
  10. public String get(String key) {
  11. myJedisSocket.send(covert(Resp.command.GET, key));
  12. return myJedisSocket.read();
  13. }
  14. public String incr(String key) {
  15. myJedisSocket.send(covert(Resp.command.INCR, key));
  16. return myJedisSocket.read();
  17. }
  18. public static String covert(Resp.command command, String... strings) {
  19. StringBuilder sb = new StringBuilder();
  20. sb.append(Resp.START).append(1 + strings.length).append(Resp.LINE);
  21. sb.append(Resp.STR_LENGTH).append(command.toString().length()).append(Resp.LINE);
  22. sb.append(command.name()).append(Resp.LINE);
  23. for (String str : strings) {
  24. sb.append(Resp.STR_LENGTH).append(str.length()).append(Resp.LINE);
  25. sb.append(str).append(Resp.LINE);
  26. }
  27. return sb.toString();
  28. }
  29. public static void main(String[] args) {
  30. MyJedis jedis = new MyJedis("127.0.0.1", 6379);
  31. System.out.println(jedis.set("test", "123456"));
  32. System.out.println(jedis.get("test"));
  33. System.out.println(jedis.incr("lock"));
  34. }
  35. }