使用Socket访问redis客户端
使用Socket访问redis客户端
import java.io.IOException; import java.net.Socket; public class RedisDemoClient { Socket redisConnection = null; public RedisDemoClient(String host, int port) throws IOException{ redisConnection = new Socket(host, port); } public void set(String key, String value) throws IOException{ StringBuilder request = new StringBuilder(); request.append("*3").append("\r\n"); request.append("$3").append("\r\n"); //参数的长度 request.append("SET").append("\r\n"); // 参数的值 request.append("$").append(key.getBytes().length).append("\r\n"); request.append(key).append("\r\n"); request.append("$").append(value.getBytes().length).append("\r\n"); request.append(value).append("\r\n"); System.out.println("这就是客户端发给redis服务器数据:"); System.out.println(request); // 发送数据到redis服务器 redisConnection.getOutputStream().write(request.toString().getBytes()); //如何接受redis服务器的相应 byte[] response = new byte[1024]; redisConnection.getInputStream().read(); } public static void main(String[] args) throws IOException{ RedisDemoClient redisDemoClient = new RedisDemoClient("127.0.0.1",6379); redisDemoClient.set("testKey", "testValue"); } }
使用console可以看到
get
public String get(String key) throws IOException { StringBuilder request = new StringBuilder(); request.append("*2").append("\r\n"); request.append("GET").append("\r\n"); request.append("$").append(key.getBytes().length).append("\r\n"); request.append(key).append("\r\n"); System.out.println("这就是客户端发送给Redis服务器的数据"); System.out.println(request); redisConnection.getOutputStream().write(request.toString().getBytes()); // 如何接受redis 服务器的响应 byte[] response = new byte[1024]; redisConnection.getInputStream().read(response); return new String(response); }
测试
redisDemoClient.get("testKey");
显示