使用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