redis 模擬jedis 操做string類型數據

 

一.思路分析

redis數據傳輸遵循resp協議,只須要按照resp協議並經過socket傳遞數據到redis服務器便可java

 

resp數據格式:redis

 

 

 

 

二.具體實現

package com.ahd.jedis;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/***
 * 模擬jedis對redis進行操做
 */
public class MyJedis {
    private Socket socket;

    public MyJedis(String url,Integer port) throws IOException {
        socket=new Socket(url,port);
    }

    public static void main(String[] args) throws IOException {
        MyJedis myJedis=new MyJedis("127.0.0.1",6379);

        //myJedis.set("sex","sdf");
        //myJedis.get("sex");
        myJedis.del("sex");
    }

    /***
     * 模擬set string類型
     * @param key
     * @param value
     */
    public void set(String key,String value) throws IOException {
        StringBuffer stringBuffer=new StringBuffer();
        //getBytes 是由於key和value多是中文,直接獲取長度會出錯
        stringBuffer.append("*3"+"\r\n")
                .append("$3"+"\r\n").append("SET"+"\r\n")
                .append("$"+key.getBytes().length+"\r\n").append(key+"\r\n")
                .append("$"+value.getBytes().length+"\r\n").append(value+"\r\n");
        OutputStream outputStream = socket.getOutputStream();

        System.out.println(stringBuffer);
        outputStream.write(stringBuffer.toString().getBytes());

    }

    /***
     * 模擬get String
     * @param key
     * @return
     */
    public String get(String key) throws IOException {
        StringBuffer stringBuffer=new StringBuffer();
        //getBytes 是由於key和value多是中文,直接獲取長度會出錯
        stringBuffer.append("*2"+"\r\n")
                .append("$3"+"\r\n").append("get"+"\r\n")
                .append("$"+key.getBytes().length+"\r\n").append(key+"\r\n");
        //1. 將命令傳遞到redis
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(stringBuffer.toString().getBytes());

        //2. 接收redis的響應結果
        InputStream inputStream = socket.getInputStream();
        byte[] b=new byte[2048];
        inputStream.read(b);

        return new String(b);
    }

    /***
     * 指定key 刪除
     * @param key
     * @return
     * @throws IOException
     */
    public void del(String key) throws IOException {
        StringBuffer stringBuffer=new StringBuffer();
        //getBytes 是由於key和value多是中文,直接獲取長度會出錯
        stringBuffer.append("*2"+"\r\n")
                .append("$3"+"\r\n").append("del"+"\r\n")
                .append("$"+key.getBytes().length+"\r\n").append(key+"\r\n");
        //1. 將命令傳遞到redis
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(stringBuffer.toString().getBytes());
        outputStream.flush();
    }

}

 

 

 

三.運行結果

 

相關文章
相關標籤/搜索