使用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");

  显示

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM