Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Write a client that can operate redis by yourself

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Author: lonely smoke Source: Wechat Subscription account (programmer lonely smoke)

Original link: https://mp.weixin.qq.com/s/IBynkex-FHhvJ3tmizvJhA

Introduction

Redis is often used in projects. The official website also provides a multilingual client for you to operate redis, as shown in the following figure

But have you ever thought about the principle behind the operation of redis in these languages? In fact, some great gods will say

As long as you send the specified data to redis according to the protocol of redis, you can listen for the returned value.

Indeed, the essential principle is as mentioned in the above sentence. In this way, the blogger took a look at the source code of jedis, the open source component of Java, and then took its essence and wrote a demo that can operate redis. I hope you can get something.

The github address of jedis is:

Https://github.com/xetorthio/jedis

Children's shoes that you are interested in can also be read by yourself. It should be noted that, after all, this is not a series of source code analysis articles, not to take you to see the jedis source code. Just learn from the idea, write a program that can operate redis.

Text

First of all, let me talk about the operation ideas, as shown in the following figure.

To be clear, the fourth step above is the small demo that we want to write to operate redis.

1. Write a socket to listen for port 6379 first.

This program is very easy. Du Niang comes out a lot at once.

Import java.io.IOException;import java.io.InputStreamReader;import java.io.Reader;import java.net.ServerSocket;import java.net.Socket;public class SocketServer {public static void main (String [] args) throws IOException {ServerSocket server = new ServerSocket (6379); Socket socket = server.accept (); byte [] chars = new byte [64]; socket.getInputStream () .read (chars); System.out.println (new String (chars)) }} 2. Use open source client to operate redis once

I use jedis of JAVA language here, and you can also use any other language components to collect the data sent by the client when operating redis.

Import redis.clients.jedis.Jedis;public class RedisTest {public static void main (String [] args) {Jedis jedis = new Jedis ("127.0.0.1", 6379); jedis.set ("eat", "I want to eat");}} 3. Look at the data monitored by socket

Run the code in step 2 here to see the data output from the code in step 1, as shown below

* 3 $3SET$3eat$13I want to eat

So what does this set of data mean?

Let's go to the official website to inquire. It turns out that the client and server of redis have adopted a RESP protocol. The corresponding document address is as follows

Https://redis.io/topics/protocol

RESP is cleverly designed, and its prospect lies in the following three aspects:

Simple to implement.

Fast to parse.

Human readable.

So what do the symbols +, -, *,:, and $mean?

There is a passage on the official website.

In RESP, the type of some data depends on the first byte: For Simple Strings the first byte of the reply is "+"

For Errors the first byte of the reply is "-"

For Integers the first byte of the reply is ":"

For Bulk Strings the first byte of the reply is "$"

For Arrays the first byte of the reply is "*"

Additionally RESP is able to represent a Null value using a special variation of Bulk Strings or Array as specified later.

In RESP different parts of the protocol are always terminated with "\ r\ n" (CRLF).

Translate it.

(1) simple string Simple Strings, starting with the "+" plus sign

(2) error Errors, starting with "-" minus sign

(3) Integer Integer, starting with ":" colon

(4) large string type Bulk Strings, starting with "$" dollar sign, with a length limit of 512m

(5) Group type Arrays, starting with "*" asterisk

Also, each part of the agreement ends with "\ r\ n" (CRLF).

OK, the meaning of the string of data we just had is (we didn't see "\ r\ n", because it has been escaped, so we can't see it):

* 3 the array contains three elements, namely, SET, eat, I want to eat$3 is a string, and the string length is 3SET string content $3 is a string, and the string length is 3eat string content $13 is a string, and the string length is the content of 13I want to eat string

Question: if it is a get command, what does the content of the transmitted RESP look like?

For example, if there is a command get eat, the content at this time is as follows

* 2 $3GET$3eat

No\ r\ nbecause it has been escaped, so I didn't see it. Other commands can be tested by yourself.

4. Try to construct the same data operation redis

OK, go through the bedding above. If we want to do a set operation on redis, we can construct the RESP protocol content of the set command, and use socket programming to send this string of content to redis. It is implemented here in socket of java, as well as in other languages.

We have a class RedisClient.java

The code is as follows

Import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;public class RedisClient {private Socket socket; private OutputStream outputStream; private InputStream inputStream; public RedisClient (String host, int port) {try {this.socket = new Socket (host,port); this.outputStream = this.socket.getOutputStream () This.inputStream = this.socket.getInputStream ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}} public String set (final String key, String value) {StringBuilder sb = new StringBuilder () / / although the output will be escaped, we still have to send it with\ r\ nsb.append ("* 3"). Append ("\ r\ n"); sb.append ("$3"). Append ("\ r\ n"); sb.append ("SET"). Append ("\ r\ n") Sb.append ("$") .append (key.length ()) .append ("\ r\ n"); sb.append (key) .append ("\ r\ n"); sb.append ("$") .append (value.length ()) .append ("\ r\ n"); sb.append (value) .append ("\ r\ n"); byte [] bytes= new byte [1024] Try {outputStream.write (sb.toString (). GetBytes ()); inputStream.read (bytes);} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} return new String (bytes) } public static void main (String [] args) {RedisClient redisClient = new RedisClient ("127.0.0.1", 6379); String result = redisClient.set ("eat", "please eat"); System.out.println (result);}}

The public String set (final String key, String value) method above shows the contents of the RESP protocol that we need to transmit if we need to set the redis. Remember, be sure to end with the\ r\ ncharacter

OK, run the above code, you will find that you can set the data into redis, and the console output is as follows

+ OK

Question, can you encapsulate the get command yourself?

Summary

This article leads you to write a demo that can operate redis in a step-by-step way. I hope you can get something.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report