redis 模拟jedis 操作string类型数据
一.思路分析
redis数据传输遵循resp协议,只需要按照resp协议并通过socket传递数据到redis服务器即可
resp数据格式:
二.具体实现
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(); } }
三.运行结果